python 调用C++,将传入的函数全局化并调用

这个问题在调用已经封装好的SDK库时遇到,我在调用海康相机的时候需要解决这个问题。python传入一个函

数到C++,调用SDK设置回调,在回调函数里面我需要将数据返回给python,就是在回调函数里面调用传入的

python函数


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
//该文件名称:cpptest.cpp
//终端下编译指令:
//g++ -o cpptest.so -shared -fPIC cpptest.cpp
typedef void (*Func)(char*);
Func pyFunc = NULL;

void getDatatoPy(){
    for(int x = 0;x < 100 ;x++){
        char string[10];
        sprintf(string,"%d",x);
        pyFunc(string);
    }
}

extern "C"{//extern “C”中的函数才能被外部调用
    int test(Func pyData){
        pyFunc = pyData;
        getDatatoPy();
        return 0;
    }
}
##python 文件
##文件名  pytest.py
import ctypes
mylib = ctypes.cdll.LoadLibrary("cpptest.so")
list_data = []

def func_called(mydata):
    print("print by python,called by cpp!")
    list_data.append(mydata)
    print(list_data)


FUNCCALLED = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p)

mylib.test(FUNCCALLED(func_called))


猜你喜欢

转载自blog.csdn.net/caobin0825/article/details/79663562