I am using python34 ctypes to load a DLL that I wrote in C. The purpose of using python to load this is to unit test each function. There exists three functions and two work fine, however, the third function calls malloc and returns a pointer to that new buffer. When I run the python module via py.test it passes the two that return an int/void but fails on the one returning the pointer. Below is the code I am using for both C and python.
C code is compiled with cl.exe cl.exe /DLL /Fetests\test.dll src\msg.c
DLLExport char * func2(char *message, unsigned int message_len) {
int size = (message_len * 2);
char *buf;
buf = (char *)malloc(size);
if(buf == NULL){
return NULL;
}
return buf;
}
Python code is executed via py.test and below is a function in the test_msg.py module
def test_message():
lib = cdll.LoadLibrary("./tests/test_dll.dll")
message = create_string_buffer(b"something")
size = c_uint(9)
func = lib.func2
func.restype = POINTER(c_wchar_p)
response = func(message, size)
assert response.contents == b"somethingsomething"
The error I am getting is on the malloc line. If i comment out the malloc I get a pointer back pointing to garbage but it asserts properly in the python code. However, if malloc is in, I get the error below:
OSError: exception: access violation writing 0x00017B52
============================= test session starts =============================
platform win32 -- Python 3.4.3 -- py-1.4.28 -- pytest-2.7.1
rootdir: E:\test-windows, inifile:
collected 3 items
tests\test_func.py .F.
================================== FAILURES ===================================
_________________________________ test_func ___________________________________
def test_message():
lib = cdll.LoadLibrary("./tests/test_dll.dll")
message = create_string_buffer(b"something")
size = c_uint(9)
func = lib.func2
func.restype = POINTER(c_wchar_p)
> response = func(message, domain)
E OSError: exception: access violation writing 0x00017B52
tests\test_func.py:18: OSError
===================== 1 failed, 2 passed in 0.09 seconds ======================
func(), but this may be a typo. - isanae/DLLdefines anLLmacro. The option to build a DLL is/LD. You probably also want/MDto link dynamically with the CRT. - Eryk Sunrestypeis wrong. It's achar *, not awchar_t **. Typically this should be eitherc_char_porPOINTER(c_char). A simplec_char_presult gets automatically converted to Pythonbytes. ThePOINTER(c_char)instance retains the address of the allocated buffer, which you may need tofree. - Eryk Sun