python ctypes 和 C++ 指针

标签 python c++ pointers ctypes

C++ 函数:

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;
  }

和我的Python代码:

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) )

返回

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

知道有什么可以帮忙吗? 我已经尝试过 POINTERbyref(),但我得到了相同的输出

最佳答案

SetParamValue 需要一个指针(void*c_void_p)作为第二个nd 参数,但您'正在传递一个int
该函数会将其解释为指针(内存地址),并且当尝试取消引用它(以获取其内容)时,它将出现段错误(访问冲突 ),因为该进程没有该地址的权限。

要解决此问题,请将正确的参数传递给函数:

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

您可以在 [Python 3]: ctypes - A foreign function library for Python 上找到更多详细信息.

关于python ctypes 和 C++ 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52424370/

相关文章:

c++ - 函数模板编译器错误

c++ - 通过套接字发送 BYTE*

python - 如何在 django 模板中对 strftime ('%I:%M %p' ) 的 Python 列表进行排序?

Python模块问题

c++ - cmake add_custom_command 失败,目标被删除

C: 当 Haystack 中找不到 Needle 时,my_strstr 返回 Needle

c++ - 我必须在 linux 的 c++ 中释放 "string* settings = new string[4]"的内存吗?

python - docker-compose 与 postgres 的 Django 连接

python - 如果我必须直接单击横幅并在另一个选项卡上打开它,如何使用 selenium 获取重定向链?

c++ - 就地随机选择算法