Spyros
Spyros

Reputation: 48626

ctypes error on com client

I am trying to create a com client to send messages to a server. I have the ole viewer definitions and created the structures(classes) in python, that are used to construct a complex structure that has more structures and enums in it.

Everything seems to be going well, but when i try to pass a SampleObject* to the client call, i get this error :

ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>:
expected LP__SampleObject instance instead of LP__SampleObject

Which seems pretty weird. What i am doing is something like(this is where i get the error) :

dialog = _SampleObject('hello', struct1, 'hi_there', struct2, 1, struct3, 1, 1, 1, 'me', 'you', 'him')
obj.COM_function( pointer(dialog) )

I've tried many things, but cannot get around that error. Any ideas ?

(obj is just a cc.CreateObject() coclass object, which works with no problems)

I really can't see the problem, even the comtype definition displays that in the interface :

( ['in'], POINTER(_SampleObject), 'pAction' ),

which fits perfectly with pointer(dialog). This is a very weird error, could it be a but on comtypes ?

Upvotes: 0

Views: 998

Answers (1)

Luke Woodward
Luke Woodward

Reputation: 64959

Are you defining the ctypes structs and unions of your arguments more than once?

If you define a Structure or Union subclass, use it in the argtypes of a C library function, redefine the structure or union and then attempt to pass an instance of the redefined class to the C function, you will get an error similar to the one you're seeing.

I took the code I used in this answer and added a (completely unnecessary) redefinition of the structure used with it. (I also changed the byref at the end to pointer - using byref gives you a different error message.) The Python code ended up as follows:

from ctypes import *

class TestStruct(Structure):
    _fields_ = [("a", c_int),
                ("array", (c_float * 4) * 30)]

slib = CDLL("slib.dll")
slib.print_struct.argtypes = [POINTER(TestStruct)]
slib.print_struct.restype = None

# Redefine the ctypes structure.
class TestStruct(Structure):
    _fields_ = [("a", c_int),
                ("array", (c_float * 4) * 30)]

t = TestStruct()

for i in range(30):
    for j in range(4):
        t.array[i][j] = i + 0.1*j

slib.print_struct(pointer(t))

When I ran this modified script, I got the following output:

C:\Users\Luke\Python stuff>slib2.py
Traceback (most recent call last):
  File "C:\Users\Luke\Python stuff\slib2.py", line 21, in <module>
    slib.print_struct(pointer(t))
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_TestStruct instance instead of LP_TestStruct

Upvotes: 2

Related Questions