python - 如何使用 C 程序的 python 回调设置参数值

标签 python c

我的Python代码,有一个C的回调函数:

global cbGetIMSI
CB_GET_IMSI  = CFUNCTYPE(None, c_char_p)
cbGetIMSI   = CB_GET_IMSI(py_getIMSI)
def py_getIMSI(imsi):
    global tc
    tc  = import(mod)
    imsi = tc.getIMSI()
    print '####### imsi = ' + imsi

并调用C函数进行注册:

lib_inf = cdll.LoadLibrary(self.libinf.get())
lib_inf.inf_regCbGetImsi(cbGetIMSI)

我的 C 代码:

typedef void (*inf_PyCbGetImsi)(char *);
int inf_regCbGetImsi(inf_PyCbGetImsi cbFn)
{
    DBG("enter [%s()]", FUNCTION);
    if (!cbFn)
    {
        return -1;
    }
    g_pyCB.getImsi = cbFn;
    return 0;
}

static int GetIMSI()
{
    int ret = 0;
    int i = 0;
    unsigned char aIMSI[15];
    DBG("[enter %s()]", __FUNCTION__);

    memset(aIMSI, 0, sizeof(aIMSI));
    if (g_pyCB.getImsi)
    {
        g_pyCB.getImsi(aIMSI);

    }
    DBG("[%s()] aIMSI = [%s]", __FUNCTION__, aIMSI);  

    return ret;
}

在 Python 中运行日志:

####### imsi = 001010123456789
in C Program:
[GetIMSI()] aIMSI = []

为什么参数的值没有改变,我该如何解决?谢谢!

最佳答案

问题出在你的线路上:

imsi = tc.getIMSI()

在这里你没有设置 imsi 的值,你只是将它重新定义为另一个“东西”,这也是你在 C 中会有的行为.

如果你想设置imsi的值,你应该使用类似strcpy的东西复制其中的值,这是可用的通过加载 libc 并使用类似 libc.strcpy(imsi, tc.getIMSI())

的东西

关于python - 如何使用 C 程序的 python 回调设置参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030403/

相关文章:

c - 为什么 scanf 不遵循带有非空白字符的文档?

c - int x = 时间(NULL); => 段错误?

python - Cloud 9 的语法错误?

python - 如何编写一个Python类型提示来指定一个带有某些参数或0个参数的Callable?

python - 'none' 无缘无故打印

php - C 中的 strtotime 函数

c - 头文件名作为参数

c - fread() 从二进制文件读取时出现意外行为

python - 如何使用Python数据框基于多个条件进行计算?

python - 如何使用networkx在两个图之间执行树交叉?