0

I'm trying to call a SimpleMotionv2 library from python using ctypes, it appears to make the call, but it always returns -1 when I feed it a valid com port.

I've built the DLL and the function I'm trying to call seems exported properly:

DLL Export Viewer Output

Somehow I'm passing the COM port number incorrectly? I'm on windows and its COM5...

The function I'm calling is smOpenBus() and is listed here:

smbus smOpenBus( const char * devicename )
{
    int handle;

    //true on first call
    if(smInitialized==smfalse)
        smBusesInit();

    //find free handle
    for(handle=0;handle<SM_MAX_BUSES;handle++)
    {
        if(smBus[handle].opened==smfalse) break;//choose this
    }
    //all handles in use
    if(handle>=SM_MAX_BUSES) return -1;

    //open bus device
    smBus[handle].bdHandle=smBDOpen(devicename);
    if(smBus[handle].bdHandle==-1) return -1;

    //success
    strncpy( smBus[handle].busDeviceName, devicename, SM_BUSDEVICENAME_LEN );
    smBus[handle].busDeviceName[SM_BUSDEVICENAME_LEN-1]=0;//null terminate string
    smBus[handle].opened=smtrue;
    return handle;
}

And my Python code is:

import ctypes as ct

dll = ct.CDLL(r'./SMv2_x64.dll')

dll.smOpenBus.argtypes = ct.c_char_p,
dll.smOpenBus.restype = ct.c_long

ret_val = dll.smOpenBus(b'COM24')
print(ret_val)

What on Earth am I doing wrong?

I've tried making the ptr of type c_wchar_p and c_char_p, adding NULL terminators and string and not... I expect to get a COM port handle return and I get -1.

Adam
  • 1
  • 1
  • [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/a/58611011/4788546). *argtype**s***, and it should be a sequence. – CristiFati Dec 12 '22 at 17:10
  • Thanks for that CristiFati! Great post. Unfortunatly I'm still returning -1. I've updated the code in the original post to be shorter. – Adam Dec 12 '22 at 17:38

1 Answers1

0

It’s argtypes (plural) and is a tuple. c_char_p is appropriate for C char*:

dll.smOpenBus.argtypes = ct.c_char_p, # comma makes a 1-tuple

Then pass a byte string:

ret_val = dll.smOpenBus(b'COM5')
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thanks for answering Mark! Unfortunately I am still returning -1... I've updated the shortened code. – Adam Dec 12 '22 at 17:37
  • Show that the code works from C with the same parameter. There’s nothing else to change from the Python side. – Mark Tolonen Dec 12 '22 at 20:59