Use Cxx.jl to call C++ shared library in Julia

Reproduced from the official Cxx.jl document.

Suppose there is an ArrayMaker.h and ArrayMaker.cpp (or .cc suffix on Linux, which is equivalent to .cpp), first compile them into a shared library:

g++ -shared -fPIC ArrayMaker.cpp -o libarraymaker.so

The result of the compilation is a libarrarmaker.so file.

Then call in Julia:

# 使用Cxx和Libdl
using Cxx, Libdl
# 把库的路径存为一个常数方便引用。pwd()是Julia当前工作目录,可以把它替换为libarraymaker.so的实际目录。
const path_to_lib = pwd();
# 添加头文件目录
addHeaderDir(path_to_lib, kind=C_System)
# 添加库目录(这里的库被称为dynamic link library),返回一个指针。
Libdl.dlopen(joinpath(path_to_lib, "libarraymaker.so"), Libdl.RTLD_GLOBAL)
# 包含头文件
cxxinclude("ArrayMaker.h")
# 现在开始正式使用库中的内容。首先声明一个class:
maker = @cxxnew ArrayMaker(5, 2.0)
# 用内部函数填充数组。
arr = @cxx maker->fillarr()
# 可以用unsafe_wrap()解析arr里的内容,返回的a就是arr里的数组。
a = unsafe_wrap(Array, arr, 5)

ArrayMaker.h :

#ifndef ARRAYMAKER_H
#define ARRAYMAKER_H

class ArrayMaker {
    
    
    private:
        int inumber;
        float fnumber;
        float* farr;
    public:
        ArrayMaker(int, float);
        float* fillarr();
};

#endif

ArrayMaker.cpp :

#include "ArrayMaker.h"
#include <iostream>

using namespace std;

ArrayMaker::ArrayMaker(int inum, float fnum) {
    
    
    cout << "Got arguments: " << inum << " and " << fnum << endl;
    inumber = inum;
    fnumber = fnum;
    farr = new float[inumber];
}

float* ArrayMaker::fillarr() {
    
    
    cout << "Filling the array" << endl;
    for (int i = 0; i < inumber; i++) {
    
    
        farr[i] = fnumber;
        fnumber *= 2;
    }
    return farr;
}

Guess you like

Origin blog.csdn.net/iamzhtr/article/details/103536917