2

关于 Python 2.5,我希望在 python 中实现以下 C 代码:

C代码:

#include <wtypes.h>

__declspec(dllexport) X_ERROR __stdcall GetAdmSize(INT* piAdmSize, CHAR** chBuf, INT iBufSize);

int iProgSize = 0;
char szProgSize[50];
char* pszProgSize = szProgSize;
error = GetAdmSize(&iProgSize, &pszProgSize, 49);

Python代码:

from ctypes import *
c_bool = c_int

x = windll.LoadLibrary("x.dll")
iProgSize = c_int()
szProgSize = create_string_buffer(50)
getAdmSize = x.AdkGetAdmSize
getAdmSize.argtypes = [POINTER(c_int), POINTER(c_char_p), c_int]
status = getAdmSize(byref(iProgSize), byref(szProgSize), 49)

但我得到以下异常:

Traceback (most recent call last):
    status = getAdmSize(byref(iProgSize), (szProgSize), 49)
ArgumentError: argument 2: <type 'exceptions.TypeError'>: expected LP_c_char_p instance instead of c_char_Array_50

我究竟做错了什么?

更新:

我试过了:

pointerToStringBuffer = cast(szProgSize, c_char_p)
status = getAdmSize(byref(iProgSize), byref(pointerToStringBuffer), 49)

但这给了我:

Traceback (most recent call last):
    status = getAdmSize(byref(iProgSize), byref(pointerToStringBuffer), 49)
WindowsError: exception: access violation reading 0x00000031

有趣的是,如果我这样称呼,我会在 C 中遇到同样的错误:

error = AdkGetAdmSize((int*)0, (char**)49, 0);

似乎我的论点可能没有正确对齐

有什么建议么?

4

2 回答 2

3

您的 C 代码的直接翻译更像是:

from ctypes import *
x = windll.LoadLibrary("x.dll")
iProgSize = c_int(0)
szProgSize = create_string_buffer(50)
pszProgSize = c_char_p(addressof(szProgSize))
getAdmSize = x.GetAdmSize
getAdmSize.argtypes = [POINTER(c_int), POINTER(c_char_p), c_int]
status = getAdmSize(byref(iProgSize), byref(pszProgSize), 49)

我测试过的假 DLL:

typedef int X_ERROR;
typedef int INT;
typedef char CHAR;

#include <string.h>

__declspec(dllexport) X_ERROR __stdcall GetAdmSize(INT* piAdmSize, CHAR** chBuf, INT iBufSize)
{
    *piAdmSize = 5;
    strcpy_s(*chBuf,iBufSize,"abcd");
    return 1;
}

结果:

>>> x.iProgSize
c_long(5)
>>> x.pszProgSize
c_char_p('abcd')
>>> x.szProgSize.value
'abcd'
于 2012-05-26T01:12:51.660 回答
0

想通了,我想。我还必须指定返回类型:

getAdmSize.restype = X_ERROR
于 2012-05-25T22:35:04.187 回答