ctypes方法

由于ctypes是python自带的库,并且用起来也方便,适合中小型项目,就记录来学习一下。
将test.cpp编译为动态链接库,这一步很重要,随时可以复制

g++ -fPIC -shared test.cpp -o test.so

cpp源文件,可以看到只需要在底部加入extern "C"即可,用add_integer_plus作为暴露给外部的函数,

#include "stdio.h"
#include "stdlib.h"

#include <bits/stdc++.h>
#include <vector>
using namespace std;

vector<int> v1;


//全局变量声明区
//函数声明区

struct {
    unsigned char a:4;
    unsigned char b:4;
}i;


vector <int> add(int c)
{
    for(i.a=1;i.a<=9;i.a++)
    {
      for(i.b=1;i.b<=9;i.b++)
      {
        if((i.a-1)/3!=(i.b-1)/3)
        {
          //printf("A=%d,B=%d\n",i.a,i.b);
          v1.push_back(i.a);
          v1.push_back(i.b);
        }
      }
    } 
    
    return v1;
}

extern "C"{
  int *add_plus(int c){
  	// 之后做个structure把长度也返回去
    vector<int> d = add(c);
    int n = d.size();
    int *buffer = new int[d.size()];
    if (!d.empty())
    {
        memcpy(buffer, &d[0], d.size()*sizeof(int));
    }
    return buffer;
  }
}


python调用

from ctypes import *

test = CDLL('./test.so').add_plus # 把add_plus函数赋值给test
test.restype=POINTER(c_int * 81) # 指针取几个数,这里还要判断
print([i for i in test(c_int(6)).contents]) # i是enumerate

test先实例化,然后接收返回的数据

更多推荐

python如何调用c++函数