简体   繁体   English

无法将字符串传递给python中dll中函数调用的char * arg

[英]Can't pass a string to char * arg of function call in dll in python

I am trying to use a dll in Python source using the ctypes. 我正在尝试使用ctypes在Python源代码中使用dll。 I began reading it from Python documentation as I am new to this. 我开始从Python文档中读取它,因为我是新手。 After successfully loading the dll in Python, when I try to pass a string to a function which expects a char * , it gives me 在Python中成功加载dll之后,当我尝试将字符串传递给期望char *的函数时,它给了我

"ValueError: Procedure probably called with too many arguments (4 bytes in excess)". “ValueError:过程可能用太多的参数调用(超过4个字节)”。

I also tried looking at other posts but couldn't resolve the problem. 我也试过看其他帖子但无法解决问题。

I tried different approaches to pas this string such as using byref() and pointer() but it didn't change the outcome. 我尝试了不同的方法来使用这个字符串,例如使用byref()pointer()但它没有改变结果。 I also tried with WINFUNCTYPE but failed. 我也试过WINFUNCTYPE但是失败了。 The dll that I'm using is windll. 我正在使用的dll是windll。

Here's a test program I wrote in python: 这是我在python中编写的测试程序:

from ctypes import *

lpDLL=WinDLL("C:\some_path\myDll.dll")
print lpDLL

IP_ADDR = create_string_buffer('192.168.100.228')
#IP_ADDR = "192.168.100.228"
#IP_ADDR = c_char_p("192.168.100.228")

print IP_ADDR, IP_ADDR.value

D_Init=lpDLL.D_Init
D_InitTester=lpDLL.D_InitTester

#D_InitTesterPrototype = WINFUNCTYPE(c_int, c_char_p)
#D_InitTesterParamFlags = ((1, "ipAddress", None),)
#D_InitTester = d_InitTesterPrototype(("D_InitTester", lpDLL), D_InitTesterParamFlags)

try:
    D_Init()
    D_InitTester("192.168.100.254")
except ValueError, msg:
    print "Init_Tester Failed"
    print msg

Here's how the D_InitTester is implemented in a cpp file which is available in dll exports, 以下是在dll导出中可用的cpp文件中实现D_InitTester的方法,

D_API int D_InitTester(char *ipAddress)
{
    int err = ERR_OK;

    if (LibsInitialized)
    {
        ...
        some code;
        ...

        else
        {
            err = hndl->ConInit(ipAddress);
        }

        if ( 0 < err )
        {
            err = ERR_NO_CONNECTION;
        }
        else
        {
        nTesters = 1;
            InstantiateAnalysisClasses();
            InitializeTesterSettings();
            if(NULL != hndl->hndlFm)
            {
                FmInitialized = true;
            }
        }
    }
    else
    {
        err = ERR_NOT_INITIALIZED;
    }
    return err;
}

Your help is greatly appreciated. 非常感谢您的帮助。

Most likely the cause of the error is a mismatch of calling conventions. 很可能导致错误的原因是调用约定不匹配。 I'm guessing your C++ DLL exports functions with cdecl convention but your use of WinDLL implies stdcall . 我猜你的C ++ DLL导出函数与cdecl约定,但你使用WinDLL意味着stdcall

Create your library like this to use cdecl : 像这样创建你的库来使用cdecl

lpDLL=CDLL("C:\some_path\myDll.dll")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM