【问题标题】:How to set value of argument using python callback for C program如何使用 C 程序的 python 回调设置参数值
【发布时间】:2016-12-08 01:39:53
【问题描述】:

我的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 = []

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

【问题讨论】:

  • 不为NULL,否则无法执行py_getIMSI。谢谢。
  • def getIMSI(): return '001010123456789'

标签: python c


【解决方案1】:

问题出在你的行上:

imsi = tc.getIMSI()

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

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

【讨论】:

    【解决方案2】:

    参考:Using ctypes to write callbacks that pass-in pointer to pointer parameters to be used as output-parameter

    像这样定义:CFUNCTYPE(c_byte, POINTER(POINTER(c_char)))

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 2013-05-21
      • 2021-05-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      相关资源
      最近更新 更多