我想在taichi中调用一个c++的库,看到之前版本可以通过ti.external_func_call调用.so文件,但是现在没有这个函数了。请问现在这个功能该怎么实现?
我们似乎还是保留了SourceBuilder,你可以参考tests/python/test_external_func.py
里的例子:
@pytest.mark.skipif(not has_clangpp(), reason='Clang not installed.')
@test_utils.test(arch=[ti.x64, ti.cuda])
def test_source_builder_from_file():
source_code = '''
extern "C" {
void add_and_mul(float *a, float *b, float *c, float *d, int *e) {
*c = (*a) + (*b);
*d = (*a) * (*b);
*e = int((*a) * (*b) + (*a));
}
void pow_int(int *a, int *b, int *c) {
int ret = 1;
for (int i = 0; i < (*b); i++)
ret = ret * (*a);
*c = ret;
}
}
'''
td = tempfile.mkdtemp()
fn = os.path.join(td, 'source.cpp')
with open(fn, 'w') as f:
f.write(source_code)
sb_bc = ti.lang.source_builder.SourceBuilder.from_file(fn)
@ti.kernel
def func_bc() -> ti.i32:
a = 2.0
b = 3.0
c = 0.0
d = 0.0
e = 3
sb_bc.add_and_mul(a, b, c, d, e)
p = 0
c_plus_d = int(c + d)
sb_bc.pow_int(c_plus_d, e, p)
return p
assert func_bc() == 11**8
shutil.rmtree(td)
谢谢!终于跑通了,终于弄好了。test的代码比较难懂,搞了半天发现忘了开ti.init。
附上代码
import os
import taichi as ti
ti.init(ti.cpu)
so = ti.lang.source_builder.SourceBuilder.from_file('tool.so')
@ti.func
def test_svd(F):
F00, F01, F10, F11 = F[0, 0], F[0, 1], F[1, 0], F[1, 1]
U00, U01, U10, U11 = 0.0, 0.0, 0.0, 0.0
s00, s01, s10, s11 = 0.0, 0.0, 0.0, 0.0
V00, V01, V10, V11 = 0.0, 0.0, 0.0, 0.0
so.svd_2(args=(F00, F01, F10, F11),
outputs=(U00, U01, U10, U11, s00, s01, s10, s11, V00, V01, V10, V11))
return ti.Matrix([[U00, U01], [U10, U11]]), ti.Matrix([[s00, s01], [s10, s11]]), ti.Matrix([[V00, V01], [V10, V11]])
@ti.kernel
def test():
F = ti.Matrix([[1.0,2.0],[1.0,2.0]])
U,sig,V = test_svd(F)
print(U,sig,V)
test()
2 个赞
点赞,这样导入外部的so函数会影响taichi程序性能么?影响自身kernel里面的并行性么?
对于外部导入的C++函数,Taichi Kernel里只会直接当成一个function call进行调用,不会对这个函数本身进行优化。至于其他部分的Taichi代码应该不受影响
2 个赞
Hello,
When I use ti.lang.source_builder.SourceBuilder.from_file() function, I got this error.
Type : void (float, float**)
parameter 1 mismatch: required=float**, provided=float*
Do you know how to solve this? I don’t understand the way of using output.
extern "C" {
void demo(float a, float *b) {
....
}
}
demo = ti.lang.source_builder.SourceBuilder.from_file('libdemo.dylib')
@ti.func
def example():
a = 0.0
b = 0.0
demo.demo(args=(a), outputs=(b))