Procedure called with not enough arguments (8 bytes missing) or wrong calling convention

小白在使用ctypes 调用 C dll 时,总是报

Procedure called with not enough arguments (8 bytes missing) or wrong calling convention

这里把网友的帮忙做一个总结,方便小白们一起查阅。

环境:

windows7 + VS2010 + python3.3

C ++ 代码如:  https://blog.csdn.net/zhang_fei_fresh/article/details/83999818

DLLTest.h

extern "C" _declspec(dllexport) int __stdcall add_a_b_c(int a, int b, int c);
extern "C" _declspec(dllexport) int __stdcall sub_a_b(int a, int b);

// DLLTest.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "DLLTest.h"

int __stdcall add_a_b_c(int a, int b, int c)
{
    return a+b+c;
}

int __stdcall sub_a_b(int a, int b)
{
    if(a > b)
        return a-b;
    else
        return 0;
}

将上述代码编译为DLLTest.dll

Python 代码

>>> from ctypes import windll
>>> somelic = windll.LoadLibrary(".\DLLTest.dll")
>>> somelic.add_a_b_c(1, 2, 3)
6

符合需求

重新写了一个测试指针的动态库,里面包含的指针函数:

    char* str2( char *src, char* dest, int len)
    {
        if (src == NULL || len <= 0)
        {
            return 0;
        }

        int src_len = strlen(src);
        printf( " %s\n", src);
        printf( " %s %s!!!\n", src, dest);
        return "test OK\n";
    }

Python 测试代码:

from ctypes import windll  #这里windll, 还有一个CDLL暂时不清楚用法

import ctypes

dll2 = windll.LoadLibrary("./PythonCtypesExample.dll")

resp = dll2.init(20)

print(resp)

print(type(resp))

 

resp2 = dll2.is_inited()

print(resp2)

print(type(resp2))

 

refer1 = ctypes.c_char_p(b"hello")

refer2 = ctypes.c_char_p(b"world")

resp3 = ctypes.c_char_p(b"")

resp3.value = dll2.str2(refer1, refer2, 10)

print(resp3.value)

print("type resp3: ")

print(type(resp3))

 

resp4 = dll2.str2(refer1, refer2, 10)

print(resp4)

print(type(resp3))

测试结果:

inited OK
0

_num = 20
1

 hello
 hello world!!!
b'test OK\n'
type resp3:

 hello
 hello world!!!
1373774060

这里需要在Python里对字符串处理下,ctypes输入和输出均为bytes类型,而个人更习惯使用string 类型。

谢谢 https://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/

你可能感兴趣的:(Python调用C/C++)