I need a portable cross-platform way to load text files at compile time. My application is a virtual machine for a domain specific language that I have written so I need the core class files to be embedded. They should not be loaded at runtime. Is this possible with C/C++ without the need of a third party library or tool.
Assume some main.cpp
file as follows.
// 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;
}
I would like the script to work in this way. Is this possible in C++ in a way that also will work with Objective-C++?
I followed the advise of @TedLyngmo to solve this problem.
I ended up writing a Python script that traversed a directory to load all of the source files of my language and generated a large C++ file containing all of the data needed to use within the virtual machine at runtime. I found resources online to help me with the API and I had some familiarity with Python. I used the os
module to get all files in a directory and the string method endswith
to test if a file had the correct extension. Finally I generated the new file via open('path/to/generated.cpp', 'w+') if the file did not exist and open('path/to/generated.cpp', 'w') if it did exist.
I have not figured out how to get Xcode to run python script at build time but I did get it to run a bash. I'll have to make adjustments later. For now this works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.