如何在C++中调用函数/类。
假设我在hello.h
中
#ifndef LIB_HELLO_GREET_H_
#define LIB_HELLO_GREET_H_
class A{
public:
int a = 0;
int b = 0;
int add(){
return a+b;
}
};
#endif
使用Bazel构建文件有一个简单的类:
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(
name = "hello",
hdrs = ["hello.h"],
)
cc_binary(
name = "hello.so",
deps = [
":hello",
],
linkshared=True,
linkstatic=False
)
在我运行Bazel build Hello.so
之后,在>中生成了共享对象文件Bazel-bin/Main
和Bazel-bin/main/hello.so.so.runfiles/__ main __/main/hello.so
。使用这些文件,我希望使用Python脚本来调用类A
。理想情况下,我想使用cppyy或类似的东西。
我已经尝试使用简单的Python脚本
import cppyy
cppyy.load_reflection_info('hello')
print(dir(cppyy.gbl))
或
import cppyy
cppyy.load_library('hello')
print(dir(cppyy.gbl))
两个.So文件,但是Cppyy似乎无法检测类A
- 它从来没有内部cppyy.gbl
我是我想知道解决这个问题的最佳方法,任何帮助都值得注意!
Let's say I have a simple class in hello.h
#ifndef LIB_HELLO_GREET_H_
#define LIB_HELLO_GREET_H_
class A{
public:
int a = 0;
int b = 0;
int add(){
return a+b;
}
};
#endif
with bazel build file:
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(
name = "hello",
hdrs = ["hello.h"],
)
cc_binary(
name = "hello.so",
deps = [
":hello",
],
linkshared=True,
linkstatic=False
)
After I run bazel build hello.so
, there is a shared object file generated in bazel-bin/main
and bazel-bin/main/hello.so.runfiles/__main__/main/hello.so
. Using those files, I want call class A
with a python script. Ideally, I'd want to use cppyy or something similar.
I've tried with simple python scripts
import cppyy
cppyy.load_reflection_info('hello')
print(dir(cppyy.gbl))
or
import cppyy
cppyy.load_library('hello')
print(dir(cppyy.gbl))
with both .so files, but cppyy can't seem to detect class A
- it is never inside cppyy.gbl
I'm wondering the best way to solve this problem, any help appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用cppyy,您还需要将其提供给标头文件,也就是说:
并且可选地使用
cppyy.add_include_path()
添加目录,其中hello.h hello.h
属于可以找到。另一种选择是使用所谓的“词典”。这些软件包(可自定义的)目录位置,必要的标头文件的名称以及(通过链接)共享库(将实现)与一个新的,新的,共享的库(由于历史记录而命名为“词典”)。侧面可以有一个所谓的“ rootmap”文件,允许类加载程序在首次使用时自动找到
a
。请参阅文档中的示例。With cppyy, you also need to give it the header file, that is:
and optionally use
cppyy.add_include_path()
to add the directory wherehello.h
resides, so that it can be found.An alternative is to use so-called "dictionaries." These package (customizable) directory locations, names of necessary headers files and (through linking) the shared library with the implementation into a single, new, shared library (named "dictionary" because of history). There can be a so-called "rootmap" file on the side that allows a class loader to find
A
automatically on first use. See the example in the documentation.