You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下用ctypes调用icx编译的DLL时找不到函数的问题

问题描述

我有一个C语言文件display.c,代码如下:

#include <stdio.h>

void display()
{
    printf("Hello, World!");
}

用以下命令编译成DLL:

icx.exe /c /EHsc display.c
xilink /DLL /OUT:libdisplay.dll display.obj

然后写了Python脚本try_ctypes.py:

import ctypes

clibrary = ctypes.CDLL(".\\libdisplay.dll")

clibrary.display()

运行时报错:AttributeError: function 'display' not found,执行print(dir(clibrary))也看不到display函数。网上教程大多讲gcc,怀疑是icx的用法有问题?

执行dumpbin libdisplay.dll的输出:

File Type: DLL

  Summary

        2000 .data
        1000 .pdata
        A000 .rdata
        1000 .reloc
        F000 .text
        1000 _RDATA

解决方案

方法1:修改C代码显式导出函数

ICX和MSVC的逻辑一致,默认不会自动把函数导出到DLL中,必须明确标记要导出的函数。修改display.c:

#include <stdio.h>

// 定义导出宏,Windows环境下用__declspec(dllexport)
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

// extern "C"确保函数名不被编译器修饰(即使是C代码,加上也能避免意外的名字变更)
extern "C" EXPORT void display()
{
    printf("Hello, World!\n");
}

重新编译:

icx.exe /c /EHsc display.c
xilink /DLL /OUT:libdisplay.dll display.obj

方法2:使用模块定义文件(.def)

如果不想修改C代码,可新建display.def文件,内容如下:

LIBRARY libdisplay
EXPORTS
    display @1

编译时带上这个def文件:

icx.exe /c /EHsc display.c
xilink /DLL /OUT:libdisplay.dll display.obj display.def

验证导出结果

执行dumpbin /exports libdisplay.dll查看导出表,能看到display条目即为成功:

File Type: DLL

  Section contains the following exports for libdisplay.dll

    00000000 characteristics
    FFFFFFFF time date stamp
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 00001000 display

此时再运行Python脚本,就能正常调用display函数了。


内容的提问来源于stack exchange,提问作者DJames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:02:21