最近我在研究用ctypes实现python调用c,按照晚上的教程写下了类似下面的c程序:
#include <stdio.h>
int nn_test(int num){
printf("input is %d\n",num);
return num*num;
}
我用gcc把它编译成nn_api.dll文件,在python里面调用:
import ctypes as ct
nn=ct.windll.LoadLibrary("./nn_api.dll")
# nn=ct.CDLL("./nn_api.dll")
print(nn.nn_test(90))
可是总遇到如下错误:
Traceback (most recent call last):
File "D:\AudioProcess\dsp_python\py_inst.py", line 5, in <module>
nn.nn_test(90)
File "C:\ProgramData\Anaconda3\lib\ctypes\__init__.py", line 395, in __getattr__
func = self.__getitem__(name)
File "C:\ProgramData\Anaconda3\lib\ctypes\__init__.py", line 400, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'nn_test' not found
我是按照https://coderslegacy.com/python/ctypes-tutorial 这个网站的教程编写的程序,可以肯定程序没有什么问题。在网上搜索了一阵后,我猜测是因为源文件里面没有添加声明导致的。于是我在c文件里面添加了如下语句:
extern"C" {
int nn_test(int num);
}
重现编译dll文件后再运行python:
input is 90
8100
终于成功了
posted on
浙公网安备 33010602011771号