python ctypes and C++ pointers

0

C++ funtion:

DLLENTRY int VTS_API
    SetParamValue( const char *paramName, void *paramValue ) //will return zero(0) in the case of an error
  {
    rtwCAPI_ModelMappingInfo* mmi = &(rtmGetDataMapInfo(PSA_StandAlone_M).mmi);
    int idx = getParamIdx( paramName );
    if (idx<0) {
      return 0;                        //Error
    }

    int retval = capi_ModifyModelParameter( mmi, idx, paramValue );
    if (retval == 1 ) {
      ParamUpdateConst();
    }

    return retval;
  }

and my Python code:

import os
from ctypes import *

print(os.getcwd())
os.chdir(r"C:\MY_SECRET_DIR")
print(os.getcwd())

PSAdll=cdll.LoadLibrary(os.getcwd()+"\PSA_StandAlone_1.dll")

setParam=PSAdll.SetParamValue
setParam.restype=c_int

setParam.argtypes=[c_char_p, c_void_p]

z=setParam(b"LDOGenSpdSetpoint", int(20) )

returns

z=setParam(b"LDO_PSA_GenSpdSetpoint01", int(20) )
WindowsError: exception: access violation reading 0x00000020

Any idea what can help? I already tried POINTER and byref(), but I am getting the same output

python
c++
pointers
ctypes
asked on Stack Overflow Sep 20, 2018 by Jakub Hachlowski • edited Sep 20, 2018 by khelwood

1 Answer

1

SetParamValue expects a pointer (void* or c_void_p) as the 2nd argument, but you're passing an int.
The function will interpret it as a pointer (memory address), and when attempting to dereference it (to get its content), it will segfault (Access Violation), as the process doesn't have permissions on that address.

To fix the problem, pass the proper arguments to the function:

z = setParam(b"LDOGenSpdSetpoint", pointer(c_int(20)))

You can find more details on [Python 3]: ctypes - A foreign function library for Python.

answered on Stack Overflow Sep 20, 2018 by CristiFati • edited Mar 12, 2019 by CristiFati

User contributions licensed under CC BY-SA 3.0