python ctypes传数组

存在C++ 编写的DLL,主要代码如下

// list 包含 string
// list float
float maxlist(char ** modul, float * images, int num) {
	const char * split = ",";    // 用来进行切割
	char * p;
	float degree = 0;

	for ( int i = 0; i < num; i++ ){
		int j = 0;
		float degreetmp = 0;
		// split  用strok函数需要用,否则会告诉你不安全,要你用strok_s替代#pragma warning (disable : 4996)
		p = strtok( modul[i] , split );
		float ptmp = std::stof(p);    // this is much better way to do it
		while( p != NULL ){
			// 进行比较
			if (images[j] != ptmp){
				degreetmp = degreetmp + 10086 * float(ptmp + images[j]);
			}else{
				degreetmp += 1;
			}
			// 比较完继续遍历
			j++;
			p = strtok( NULL , split);
			if ( p != NULL)
				ptmp = std::stof(p);		
		}
		degreetmp = float(degreetmp/ j);
		if (degreetmp > degree){
			degree = degreetmp;
		}
	}
	return degree;
}

对应的python调用方法如下

from ctypes import *
 
module = ['2.0, 2.0, 2.0, 2.0, 2.00', '2.0, 5.0, 2.4, 2.1, 2.0', '3.0, 1.0, 2.0, 2.5, 2.00']
hist = [2, 2, 2, 2, 2]
# print len(module)
test = str(module)[1:-1]
test_1 = str(hist)[1:-1]
list_test = []

# 这里简单粗暴一下,复制了三次。。。
list_test.append(test.replace(' ', ''))
list_test.append(test.replace(' ', ''))
list_test.append(test.replace(' ', ''))

test_2 = (c_char_p*3)()
for i in xrange(0, 3):
    # 这里给的是地址
    test_2[i] = list_test[i]
 
test2 = (c_float*5)()
for i in xrange(0, 5):
    # 这里给的是数字
    test2[i] = hist[i]
 
test_ = cdll.LoadLibrary("dll.dll")
 
test_.maxlist.restype = c_float
results1 = test_.maxlist(test_2, test2, 3)
print "result1:", results1

猜你喜欢

转载自blog.csdn.net/cahesi/article/details/80256638
今日推荐