传入两个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