python 3 调用c/c++ 动态链接库 *.dll

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/iceboy314159/article/details/53192175

首先,创建动态链接库(一个简单的北斗数据处理接口,为简化处理,实现部分直接返回值),代码如下:

#ifndef _pro_header_2014_
#define _pro_header_2014_

#ifdef EXPORT_PRO_DLL
#define PRO_API __declspec(dllexport)
#else
#define PRO_API __declspec(dllimport)
#endif

struct StructResult
{
    double x;
    double y;
    double z;
    char rover[120];
    char reference[120];
};
extern "C"
{
    PRO_API int doPostRtk(struct StructResult* pxResult);
}
#endif // !_pro_header_2014_

#define EXPORT_PRO_DLL

#include "pro.h"
#include "string.h"
PRO_API int doPostRtk(struct StructResult* pxResult)
{
    if (strcmp(pxResult->reference, pxResult->rover))
    {
        pxResult->x = 1.2;
        pxResult->y = 3.6;
        pxResult->z = 9.6;
    }
    else
    {
        return -1;
    }

    return 0;
}

调用动态链接库的python代码如下(python 3):

'''
a demo for python call c/c++ *.dll module
'''
from ctypes import *

def calldll():
    class CResults(Structure):
        _fields_=[
            ("x",c_double),
            ("y",c_double),
            ("z",c_double),
            ("rov",c_char* 120),
            ("ref",c_char* 120),
            ]
    #此处应与动态库调用convention一致
    #dll = windll.LoadLibrary('process.dll');
    dll = cdll.process
    postRtk = dll.doPostRtk
    postRtk.restype = c_int
    postRtk.argtypes = [POINTER(CResults)]
    objectStruct = CResults()
    objectStruct.rov = bytes("C:\\xq\\coding\\testf\\x64\\Release\\rov.13o",'utf-8')
    objectStruct.ref = bytes("C:\\xq\coding\\testf\\x64\\Release\\ref.13o",'utf-8')
    print (objectStruct.rov)
    print (objectStruct.ref)
    ret = postRtk(byref(objectStruct))
    print ('ret:%d x:%.2f y:%.2f z:%.2f rov:%s ref:%s' %(ret,objectStruct.x,objectStruct.y,objectStruct.z,objectStruct.rov,objectStruct.ref))

if __name__ == '__main__':
    calldll()


可能会遇到的问题:

1. 使用64-bit的python 无法调用 32-bit的*.dll
   命令行输入python  可查看是否64-bit

   若是64-bit版本,可修改生成动态库时的配置,生成64-bit动态库
2. vs下可查看动态库的调用convention, python加载动态库时应与其一致。查看位置property pages-c/c++-Advanced-Calling Convention



展开阅读全文

没有更多推荐了,返回首页