Is there a way to receive the return value in Python through the OUT parameter in C++?

456 views Asked by At

I have a C++ dll, one of the export function is defined as follows:

OPERATEMYSQLSTDCALL_API  int __stdcall CheckMac(char * pcMac, OUT  LPSTR errorInfo);

I use it in python, use the ctypes library,i read some of the information and call it as follws:

from ctypes import *
lib = WinDLL('OperateMysqlStdcall.dll')
CheckMac = lib.CheckMac
CheckMac.argtypes = [c_char_p, POINTER(c_wchar_p)]
CheckMac.restype = c_int
p1=c_wchar_p()
value = CheckMac('88888888',byref(p1));
print  p1.value

but when i execute it,it return None,i'm sure the value "OUT LPSTR errorInfo" in C++ is not NULL,i print it in console and it shows Correctly.could anyone tells me why it can't work in python.Thank U very much!

1

There are 1 answers

1
Mark Tolonen On

The type of LPSTR is char* so you should use c_char_p for its type as well. As an output parameter, though, you need a writable string buffer. Ideally, the API should indicate the size of the buffer passed so a buffer overrun could be checked.

Here's some test DLL code:

#include <windows.h>

extern "C" __declspec(dllexport)
int __stdcall CheckMac(char* pcMac, LPSTR errorInfo)
{
    strcpy(errorInfo, pcMac);
    return 1;
}

And Python:

from ctypes import *
lib = WinDLL('test.dll')
CheckMac = lib.CheckMac
CheckMac.argtypes = [c_char_p, c_char_p]
CheckMac.restype = c_int
errorInfo = create_string_buffer(1024)
value = CheckMac('88888888',errorInfo);
print errorInfo.value

Output:

88888888