如何将c struct中的c_char_p传递给CDLL导出函数

时间:2014-12-30 11:01:14

标签: python c ctypes dllimport

有一些从dll导入的函数:foo

为简单起见,功能" foo"做下一件事:

# c code
struct bar {
    char *s1;
    char *s2;
};

int foo(struct bar *aBarPtr)
{
    if (NULL != aBarPtr) {
        aBarPtr->s1 = "Some static string";
        aBarPtr->s2 = "Some static string2";
    }

    return 0;
}

在Python中我创建结构:

# Python code
class BAR(Structure):
    _fields_ = [
        ("s1", c_char_p),
        ("s2", c_char_p)
    ]

并致电功能:

# Python code
FOO = my_dll_handle.foo
FOO.argtypes = [POINTER(BAR)]
bar_elem = BAR(c_char_p(), c_char_p())
retcode = FOO(byref(bar_elem))

但是在调用之后,bar_elem中的s1和s2指向None,但不指向DLL中的某些字符串。

如何解决?

1 个答案:

答案 0 :(得分:1)

没有几行来编译和运行代码,它可以工作:

X.DLL

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#endif

struct bar {
    char *s1;
    char *s2;
};

EXPORT int foo(struct bar *aBarPtr)
{
    if (aBarPtr) {
        aBarPtr->s1 = "Some static string";
        aBarPtr->s2 = "Some static string2";
    }

    return 0;
}

的Python

from ctypes import *
class BAR(Structure):
    _fields_ = [
        ("s1", c_char_p),
        ("s2", c_char_p)
    ]

foo = CDLL('x').foo
foo.argtypes = [POINTER(BAR)]
bar = BAR()
print(foo(byref(bar)))
print(bar.s1)
print(bar.s2)

输出

0
b'Some static string'
b'Some static string2'