#include<iostream>
#include<string.h>
using namespace std;
//该文件名称:cpptest.cpp
//终端下编译指令:
//g++ -o cpptest.so -shared -fPIC cpptest.cpp
typedef unsigned char byte;
struct sub_Struct{
int sub_test_int;
char sub_test_char_arr[300];
};
struct NET_DVR_ALARMER{
int test_int;
char char_array[123];
sub_Struct test_sub_struct;
byte *byte_test_p;
};
typedef void (*Fun)(long,NET_DVR_ALARMER*,void*,char*);//定义一个函数指针类型
Fun p = NULL;//定义一Fun函数
extern "C"{//在extern “C”中的函数才能被外部调用
int callback_fun(Fun pCallback,void *pp){
cout << "cpp中调用函数已经执行"<<endl;
p = pCallback;
long long_type = 3;
cout<<"实例化一个报警信息结构体"<<endl;
NET_DVR_ALARMER struct_type;
cout << "给结构体指针中的int型数据赋值"<<endl;
struct_type.test_int = 10;
cout << "结构体中的int型数据赋值成功"<<endl;
strcpy(struct_type.char_array,"char* of struct");
cout<< "结构体中的char* 型数据赋值成功"<< endl;
char* char_string =new char[255];
strcpy(char_string,"char* translate ok!");
struct_type.test_sub_struct.sub_test_int = 20;
cout<<"子结构体赋值,第一个结构体int型成员,赋值20"<<endl;
strcpy(struct_type.test_sub_struct.sub_test_char_arr,"子结构体中的字符数组赋值!!");
(*p)(long_type,&struct_type,NULL,char_string);
cout<<"cpp中调用函数已经执行完成\n\n\n\n\n\n\n"<<endl;
return 0;
}
}
##python 文件
##文件名 pytest.py
import ctypes
mylib = ctypes.cdll.LoadLibrary("cpptest.so")
##嵌套结构体测试,子结构体
class sub_Struct(ctypes.Structure):
_fields_ = [
("sub_test_int",ctypes.c_int),
("sub_test_char_arr",ctypes.c_char*300)
]
#报警设备信息结构体
class NET_DVR_ALARMER(ctypes.Structure):
_fields_ = [
("test_int", ctypes.c_int),
("char_array", ctypes.c_char*123),
("test_sub_struct",sub_Struct),
("byte_test_p",ctypes.POINTER(ctypes.c_byte))
]
CALLFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p,ctypes.c_long,ctypes.POINTER(NET_DVR_ALARMER),ctypes.c_void_p,ctypes.c_char_p)#这个是回调函数的参数
def callbackMsg(type_long,type_struct,type_void_p,char_add):
print("在python里面调用了函数")
print("在python中传递一个long型值,传来的是3,结果是:"+str(type_long))
print("结构体读取,int型变量读取:"+str(type_struct.contents.test_int))
print("结构体读取,char*变量:"+ str(type_struct.contents.char_array.decode()))
print("子结构体中的int型读取,应该是20,实际是:"+str(type_struct.contents.test_sub_struct.sub_test_int))
print("子结构体中的char[300]读取,结果是:"+str(type_struct.contents.test_sub_struct.sub_test_char_arr.decode()))
print("结构体中传来的一个byte型:"+ str(type_struct.contents.byte_test_p))
print("在回调中传来了一个空指针:"+ str(type_void_p))
print("在回调中传来了一个char*字符"+str(char_add.decode()))
mylib.callback_fun(CALLFUNC(callbackMsg),None)