3

I'd like to use a function that is defined in a DLL from Python. The value returned from the C++ function (get_version) is a struct

typedef struct myStruct {
    size_t size;
    char * buff;
} myStruct ;

The Python code is:

lib = CDLL(myDLL.dll)
lib.get_version

The question is how do I handle the returned value?

I've read Voo's answer and reading other posts, but I'm still struggling with this

I declared the struct class (Foo, from Voo's answer) and set the restype The code now looks

class Foo(Structure):
    _fields_ = [('size', c_size_t), ('buff', c_char_p)]

lib = CDLL(myDLL.dll)
lib.get_version
lib.get_version.restype = Foo._fields_

I get the following error TypeError: restype must be a type, a callable, or None

I read about this and if I set the restype not as a list, e.g.: c_char_p, the error doesn't appear

When I set the restype

lib.restype = Foo.fields

The error doesn't appear but the restype for get_version is not set correctly When looking at the variables in debug:

lib.restype = list: [('size', ), ('buff', )]

lib.get_version.restype = PyCSimpleType:

Any help would be appreciated

2
  • ctypes works with C functions, so if using C++ make sure to extern "C" the function. Commented Jun 25, 2012 at 2:30
  • Hi, can you tell me please what is return type of function in dll? I've tried with my myStruct but get error: C linkage function cannot return C++ class 'myStruct ' Commented Dec 25, 2013 at 9:42

1 Answer 1

2

You'll have to use the ctypes module. You'll just have to define the struct in your python code with ctypes.

Something like:

>>> from ctypes import *
>>> class Foo(Structure):
...     _fields_ = [("size", c_size_t), ("buff", c_char_p)]

should do the trick. Then you just set the restype of your get_version method to your struct so that the interpreter knows what it does return and then you can use it as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help, I read other posts on the issue but I'm still struggling with this. I've add more information on the original question
@user1478497 You have to set the restype value of the method not the whole dll. Also you shouldn't point it to _fields_ but the struct itself, i.e. lib.get_version.restype = Foo. Finally you probably should use a better name than foo ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.