Python 调用C++函数

传入两个int参数,返回int结果

代码

python 代码

# encoding=utf8

import ctypes

ll = ctypes.cdll.LoadLibrary
lib = ll("cpp_test/x64/Release/cpp_test.dll")

print lib.Add(1,3)

MyDLL.cpp

#include <iostream>
using namespace std; 
#include "MyDLL.h" 

int Add(int a,int b) 
{ 
    return a+b;  
} 

MyDLL.h 代码

#pragma once 

extern "C" __declspec(dllexport) int Add(int a,int b); 

运行结果

这里写图片描述


传入两个int参数的引用,返回int结果,并修改一个参数值

代码

python 代码

# encoding=utf8

import ctypes

ll = ctypes.cdll.LoadLibrary
lib = ll("cpp_test/x64/Release/cpp_test.dll")

a = ctypes.c_int(0)
b = ctypes.c_int(1)
print lib.Add(ctypes.byref(a),ctypes.byref(b))

c = a.value
print c

MyDLL.cpp

#include <iostream>
using namespace std; 
#include "MyDLL.h" 

int Add(int& a,int& b) 
{ 
    a += 1;
    return a+b;  
}

MyDLL.h 代码

#pragma once 

extern "C" __declspec(dllexport) int Add(int& a,int& b);

运行结果

这里写图片描述


传入数组,返回int结果

代码

python 代码

# encoding=utf8

import ctypes

ll = ctypes.cdll.LoadLibrary
lib = ll("cpp_test/x64/Release/cpp_test.dll")

python_array = (1,2,3,4,5)
length = len(python_array)

c_array = (ctypes.c_int * length)()
for i in xrange(length):
    c_array[i] = python_array[i]

print lib.Add(c_array,length)

MyDLL.cpp

#include <iostream>
using namespace std; 
#include "MyDLL.h" 

int Add(int* myarray,int length) 
{ 
    int result = 0;

    for(int i=0;i<length;i++)
        result += myarray[i];

    return result;  
} 

MyDLL.h 代码

#pragma once 

extern "C" __declspec(dllexport) int Add(int* myarray,int length);  

运行结果

这里写图片描述


参考资料

VS2012生成DLL
http://www.cnblogs.com/woshitianma/p/3681403.html
详细介绍ctypes
http://blog.csdn.net/jhonguy/article/details/7698350

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值