繁体   English   中英

我需要能够在编译时使用 C++ 将文件加载到字符串中吗?

[英]I need to be able to load files into a string a compile time with C++?

我需要一种可移植的跨平台方式来在编译时加载文本文件。 我的应用程序是我编写的域特定语言的虚拟机,因此我需要嵌入核心类文件。 它们不应在运行时加载。 在不需要第三方库或工具的情况下,这是否可以通过 C/C++ 实现。

假设一些main.cpp文件如下。

// load some core script
static constexpr std::string coreScript = LOAD_FILE("/path/to/lib/com/example/Person.mylang");

// main()
int main()
{
    // some setup function that returns an instance of the FFI
    MyLangEnv *env = mlvm_setup(); // some setup function that returns an instance of the FFI

    // register native Person type
    env->native()->type("com/example/Person", &Person::construct)
    ->property("firstName", &Person::firstName)
    ->property("lastName", &Person::lastName)
    ->property("age", &Person::age)
    ->method("speak", &Person::speak);
    ;

    // run script so that the class is exposed to runtime
    env->run()->mylangScript(coreScript);

    // now person can be instantiated
    Person *person = env->make()->object("com/example/Person", "Jane", "Doe", 22);
    assert(person);

    // set global
    env->set()->global("person", person);

    // eval
    env->eval("print(person.firstName)"); // outputs "Jane"

    // call speak()
    env->call()->property(person, "speak");


    // run gc() and destroy environment
    env->kill();
    return 0;
}

我希望脚本以这种方式工作。 这在 C++ 中是否可能以同样适用于 Objective-C++ 的方式实现?

我按照@TedLyngmo 的建议解决了这个问题。

我最终编写了一个 Python 脚本,该脚本遍历一个目录以加载我的语言的所有源文件,并生成一个大型 C++ 文件,其中包含运行时在虚拟机中使用所需的所有数据。 我在网上找到了可以帮助我使用 API 的资源,并且我对 Python 有一定的了解。 我使用os模块获取目录中的所有文件,并使用字符串方法endswith以测试文件是否具有正确的扩展名。 最后我通过 open('path/to/generated.cpp', 'w+') 如果文件不存在和 open('path/to/generated.cpp', 'w') 如果它确实存在生成新文件.

我还没有想出如何让 Xcode 在构建时运行 python 脚本,但我确实让它运行了 bash。 稍后我将不得不进行调整。 现在这工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM