Vladimir
Vladimir

Reputation: 33

Python dll function return wrong value

Using C# I call the dll function as follows:

[DllImport("Tnzv01.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern unsafe int TnzDDBOpenDatabase(byte[] dbFile, out IntPtr dbhDatabase);

var dbFile = Encoding.ASCII.GetBytes(FilePath);
var errorCode = TnzDDBOpenDatabase(dbFile, out var dbHandle);

It returns errorCode = 0 and dbHandle = 0x140e0690

I'm trying to do this with python:

dll = ctypes.CDLL(os.path.join("dependence", "Tnzv01.dll"))
tzh_file = bytes(r"D:\PycharmProjects\tnz_analysis_32\new_3000_57_63_421_461_464_2485.tzh", 'ASCII')
open_db_fun = dll.TnzDDBOpenDatabase
open_db_fun.restype = ctypes.c_int
open_db_fun.argtypes = [ctypes.c_byte * 70, ctypes.POINTER(ctypes.c_int)]
handle = ctypes.c_int(0)
c_tzh_file = (ctypes.c_byte * len(tzh_file))(*tzh_file)
result = open_db_fun(c_tzh_file, handle)

But it returnsresult = -2147352576 and handle = c_long(-1)

Why is python giving the wrong result?

Upvotes: 0

Views: 135

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177674

It would be more useful to see the actual C prototype, but try the following:

dll = ctypes.CDLL(os.path.join("dependence", "Tnzv01.dll"))
tzh_file = rb"D:\PycharmProjects\tnz_analysis_32\new_3000_57_63_421_461_464_2485.tzh"
open_db_fun = dll.TnzDDBOpenDatabase
open_db_fun.restype = ctypes.c_int
open_db_fun.argtypes = ctypes.c_char_p,ctypes.POINTER(ctypes.c_void_p)
handle = ctypes.c_void_p()
result = open_db_fun(tzh_file,ctypes.byref(handle))

You may pass the byte string directly assuming the C type for the first parameter is const char* and the second parameter is something like HANDLE*. Handles are generally void* under the covers and pointers are 64-bit and ctypes.c_int is only 32-bit. Pass the second parameter by reference since it is an out parameter.

Upvotes: 1

Related Questions