您现在的位置是:首页 >技术交流 >Julia系列14:调用自定义C/C++库网站首页技术交流
Julia系列14:调用自定义C/C++库
简介Julia系列14:调用自定义C/C++库
1. 基础调用:ccall
调用的基本格式为:
ccall((:函数名, 库地址), 输出格式, (输入格式列表), 输入数据)
下面是例子:
1.1 基础数据结构
1.2 数组
首先是输入数组,注意需要convert
接着是输出数组,需要使用unsafe_wrap进行转换,并且需要用GC.@perserve防止垃圾回收
二维数组需要在C中注意编号
1.3 字符串
1.4 复杂数据结构
2. AST分析:Clang.jl
假设我们有一个头文件:
// example.h
struct ExStruct {
int kind;
char* name;
float* data;
};
void* ExFunction (int kind, char* name, float* data) {
struct ExStruct st;
st.kind = kind;
st.name = name;
st.data = data;
}
使用julia查看和分析头文件的代码为:
julia> using Clang
julia> trans_unit = Clang.parse_header(Index(), "example.h")
TranslationUnit(Ptr{Nothing} @0x00007fe13cdc8a00, Index(Ptr{Nothing} @0x00007fe13cc8dde0, 0, 1))
julia> root_cursor = Clang.getTranslationUnitCursor(trans_unit)
CLCursor (CLTranslationUnit) example.h
julia> struct_cursor = search(root_cursor, "ExStruct") |> only
CLCursor (CLStructDecl) ExStruct
julia> for c in children(struct_cursor) # print children
println("Cursor: ", c, "
Kind: ", kind(c), "
Name: ", name(c), "
Type: ", Clang.getCursorType(c))
end
Cursor: CLCursor (CLFieldDecl) kind
Kind: CXCursor_FieldDecl(6)
Name: kind
Type: CLType (CLInt)
Cursor: CLCursor (CLFieldDecl) name
Kind: CXCursor_FieldDecl(6)
Name: name
Type: CLType (CLPointer)
Cursor: CLCursor (CLFieldDecl) data
Kind: CXCursor_FieldDecl(6)
Name: data
Type: CLType (CLPointer)
TranslationUnit是AST的入口,包含3部分内容:
Kind: purpose of cursor node
Type: type of the object represented by cursor
Children: list of child nodes
Clang.getTranslationUnitCursor方法可以获得其根节点。
接下来是获取方法详情:
julia> using Clang.LibClang # CXCursor_FunctionDecl is exposed from LibClang
julia> fdecl = search(root_cursor, CXCursor_FunctionDecl) |> only
CLCursor (CLFunctionDecl) ExFunction(int, char *, float *)
julia> fdecl_children = [c for c in children(fdecl)]
4-element Array{CLCursor,1}:
CLCursor (CLParmDecl) kind
CLCursor (CLParmDecl) name
CLCursor (CLParmDecl) data
CLCursor (CLCompoundStmt)
julia> [Clang.getCursorType(t) for t in fdecl_children[1:3]]
3-element Array{CLType,1}:
CLType (CLInt)
CLType (CLPointer)
CLType (CLPointer)
julia> [Clang.getPointeeType(Clang.getCursorType(t)) for t in fdecl_children[2:3]]
2-element Array{CLType,1}:
CLType (CLChar_S)
CLType (CLFloat)
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。