本文作为Python调用c++的进阶实现,简单的实现参考文章Python调用c++高级(swig)
1 一个小小的工作目标
通过Python调用c++文件,生成一个序列,包含10个随机的(0,1)序列,涉及到python为c++函数提供指针型变量和数组型变量。
2 c++实现
c++实现的头文件:
//DataGen.h
#ifndef DATAGEN_H
#define DATAGEN_H
#include <stdio.h>
#include <stdlib.h>
#define FrameLen 1024
#define MASK 12349876
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
//#include "101_UserType.h"
//#include "102_UserDefine.h"
double ran0(long *idum);
double GaussNoise(double Sigma, long *idum);
void randombit_gene(int *output, int length, long *seed);
int randint(long *idum);
#endif
c++实现的源文件:
//DataGen.cpp
#include "DataGen.h"
//函数实现
c++实现生成长度为10的int型数组:
#include <iostream>
#include "../DataGen.h"
using namespace std;
long SeEd=1234;
int main()
{
int *SourceBit = new int[FrameLen];
randombit_gene(SourceBit, FrameLen, &SeEd);
delete [] SourceBit;
return 0;
}
实现过程为:
- 生成一个long*的指针作为随机产生器的种子;
- 初始化生成一个长度为FrameLen的int型数组SourceBits;
- 调用c++函数randombit_gene(SourceBits, FrameLen, &SeEd);
3 Python中调用randombit_gene函数
先直接给出swig配置文件(之后使用命令行生成动态链接库.so文件)和Python执行文件
/* File: DataGen.i */
%module DataGen
//用来生成指针
%include "cpointer.i"
//用来生成数组
%include "carrays.i"
%pointer_class(long, long_p);
%array_class(int, intArray);