我正在尝试将用C代码编写的函数导入python。我尝试过的一个最小示例是
//test.h
__declspec(dllexport) int HW(int, int);
//test.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
__declspec(dllexport) int HW(int a, int b)
{
return a + b;
}
我也试图删除两个文件中的__declspec(dllexport)
。然后我在Visual Studio 2019 CMD中执行了以下操作
cl /LD test.c
或
cl /LD test.c \libs\python37.lib
在python中,我做了
from ctypes import *
a = CDLL('test.dll')
事实证明,硬件不是a的属性。我做错了哪一部分?
您需要的最低代码如下。 test.h
不需要导出功能,也没有使用任何其他包含。
__declspec(dllexport) int HW(int a, int b)
{
return a + b;
}
使用cl /LD test.c
进行编译(Microsoft)。不需要python库。如果使用32位Python,请确保使用32位编译器;如果使用64位Python,请确保使用64位编译器。
使用演示:
>>> from ctypes import *
>>> a = CDLL('./test')
>>> a.HW
<_FuncPtr object at 0x000001E44AB7BA00>
>>> a.HW(1,2)
3
注意,只有一次访问该功能,您才能通过检查(即dir(a)
)查看该功能:
>>> from ctypes import *
>>> a = CDLL('./test')
>>> dir(a)
['_FuncPtr', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_func_flags_', '_func_restype_', '_handle', '_name']
>>> a.HW
<_FuncPtr object at 0x0000020A92B7B930>
>>> dir(a)
['HW', '_FuncPtr', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_func_flags_', '_func_restype_', '_handle', '_name']