guidout
guidout

Reputation: 342

Pass object to DLL function imported with ctypes

I need to use an existing library in my python application. This is a library to read a particular data file. If you are curious you can download it from here https://www.hbm.com/en/2082/somat-download-archive/ (somat libsie).

The first thing I need to do it open the file so my python scripts starts like:

import ctypes

hllDll = ctypes.WinDLL(r"libsie.dll")
context = hllDll.sie_context_new()
file = hllDll.sie_file_open(context, "test.sie".encode())

but I get the following error:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.3.5\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
OSError: exception: access violation reading 0x000000009F6C06B8

I verified that the .sie file is accessible. I think the problem lies in the "context" object that gets passed as first argument. I think the type is the issue.

Here is part of the header file where context is defined:

typedef void sie_Context;
...
SIE_DECLARE(sie_Context *) sie_context_new(void);
/* > Returns a new library context. */ 

Am I calling these functions correctly? Is there a problem with passing the context object?

Thanks in advance

Upvotes: 0

Views: 420

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177674

On a 64-bit system, return values default to c_int (32-bit). At a minimum, set the .restype to at least a c_void_p to indicate a 64-bit pointer is returned.

Ideally, set .argtypes and .restype for each function called.

import ctypes

hllDll = ctypes.WinDLL(r"libsie.dll")
hllDll.sie_context_new.argtypes = () # optional but recommended
hllDll.sie_context_new.restype = ctypes.c_void_p  # add this
hllDll.sie_context_new.argtypes = ctypes.c_void_p, ctypes.c_char_p # guess, need prototype
# hllDll.sie_context_new.restype = ???

context = hllDll.sie_context_new()
file = hllDll.sie_file_open(context, b"test.sie")

Upvotes: 1

Related Questions