gpt4 book ai didi

c++ - 使用带有 python 的 DLL(使用 ctypes),不工作

转载 作者:太空狗 更新时间:2023-10-29 20:28:54 24 4
gpt4 key购买 nike

我正在尝试编写一个可以在 Python (2.7) 中导入的 DLL,但我在“让它工作”时遇到了困难。当我使用 WinDLL()windll.LoadLibrary() 在 Python 中加载库并测试导出的函数时,我得到的输出为空。如果我向 TestFunction() 添加一个参数,它会引发一个 ValueError,它指出可能有很多参数(实际上不是)。

python 文件:

from ctypes import *

x = windll.LoadLibrary('./pymod.dll')
print x.TestFunction(123) #Should return 123.

ma​​in.h:

#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
#define DLL_EXPORT __declspec(dllexport)

#ifdef __cplusplus
extern "C"
{
#endif

int DLL_EXPORT TestFunction(int data);

#ifdef __cplusplus
}
#endif

#endif

ma​​in.cpp:

#include "main.h"

int DLL_EXPORT TestFunction(int x = 0) {
return x;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
switch (fdwReason){
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}

已解决:问题是错误的调用约定。

最佳答案

我的第一个猜测是您使用的调用约定与 Python 假定的不同。

int DLL_EXPORT TestFunction(int data);

该声明可能意味着将使用cdecl 调用约定;而 windll 的使用使 Python 相信应该使用 stdcall 约定。这有效地改变了传递参数的方式,从而使 Python 认为您传递了错误数量的参数。这在 ctypes documentation 中有说明。 .

如果是这种情况,您可以执行以下任一操作:

  1. 将C 代码中的调用约定更改为stdcall(在Windows 系统DLL 中使用)。如果你使用的是 MSVC,他们有 a doc on developing DLLs ;
  2. 将 Python 代码期望的调用约定更改为 cdecl。这是通过使用 cdll 而不是 windll 来完成的。

关于c++ - 使用带有 python 的 DLL(使用 ctypes),不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11769780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com