1 回答
TA贡献1820条经验 获得超9个赞
您必须为每个函数定义所有参数。这是一个工作示例:
测试.cpp
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
#include <stdio.h>
struct special_object {
special_object() {
printf("created\n");
}
~special_object() {
printf("destroyed\n");
}
void print(char* buffer, int buffer_size) {
for(int i = 0; i < buffer_size; i++)
printf("%02X ",static_cast<unsigned char>(buffer[i]));
printf("\n");
}
};
extern "C" {
API special_object *special_object_new() {
return new special_object();
}
API void special_object_print(special_object *O, char *buffer, int buffer_size) {
O->print(buffer, buffer_size);
}
API void special_object_delete(special_object *O) {
delete O;
}
}
测试文件
from ctypes import *
lib = CDLL('test')
lib.special_object_new.argtypes = ()
lib.special_object_new.restype = c_void_p
lib.special_object_print.argtypes = c_void_p, c_char_p, c_int
lib.special_object_print.restype = None
lib.special_object_delete.argtypes = c_void_p,
lib.special_object_delete.restype = None
class Special:
def __init__(self):
self.obj = lib.special_object_new()
def __del__(self):
lib.special_object_delete(self.obj)
def print(self,buffer):
lib.special_object_print(self.obj,buffer,len(buffer))
s = Special()
s.print(bytes([0x01,0x02,0xaa,0x55]))
s.print(b'hello, world!')
输出:
created
01 02 AA 55
68 65 6C 6C 6F 2C 20 77 6F 72 6C 64 21
destroyed
添加回答
举报