I'm trying to write a Python wrapper using Ctypes for a pre-written DLL file but keep struggling with a pointer issue.
Specifically, a simplified example of my C++ function that's been compiled into the DLL is:
double compute_result(double var1, double var2, char *output_message1, char *output_message2){
// Computational steps are all here, e.g.
double result = var1 + var2;
// then an information message is passed to the output_message1 & 2 location
sprintf(output_message1, "useful output message 1");
sprintf(output_message2, "useful output message 2");
return(result);
}
To wrap this using ctypes, I've tried to define the appropriate restype and argtype as follows. The C++ code doesn't specify a size for the output message pointer so I assume I don't have to using ctypes.
dll = ctypes.WinDLL("MyDLL.dll")
f = dll.compute_result
f.restype = c_double
f.argtypes = [c_double, c_double, POINTER(c_char), POINTER(c_char)]
I then try calling my code in Python using:
# Imports
import ctypes
from ctypes import c_double, c_char, POINTER, addressof, cast
# Input variables
var1 = 1.1
var2 = 2.2
# Create string buffers to hold output message, then convert address to a pointer to pass to dll function
size = 1024 # we know output messages will be shorter than 1024 characters
buf1 = ctypes.create_string_buffer(size)
buf2 = ctypes.create_string_buffer(size)
f(var1, var2, cast(addressof(buf1), POINTER(c_char)), cast(addressof(buf2), POINTER(c_char)))
Unfortunately, a dialog box error is displayed upon execution, saying:
"Debug Assertion Failed!"
Program: ...somepath_on_my_computer\python.exe
File: ...somepath_on_my_computer\sprintf.c
Line: 110
Expression: (string != NULL)
I understand that this implies some error with my pointers where sprintf is meant to write the output message too, but I can't see what exactly is wrong. Is there a way to fix this please? Or am I handling pointers incorrectly? Thanks!