I want to pass a variable from AngelScript to C++.
I already managed to pass functions from AngelScript to C++ and vice versa.
I also can pass variables from C++ to AngelScript, however I can't figure out how to do it the other way round.
The manual didn't help me or I have overseen that part.
Can you please give me a hint?
Edit:
As mentioned in the comment here is what I already managed to do.
in my test.as file:
int add(int a, int b)
{
print("Hello World, I'm AngelScript\n");
multi(5, 13);
print("c is " + c + "\n");
return (a + b);
}
my test.cpp file:
int multi(int x, int y)
{
int z = x * y;
cout << "x aus dem Skript: " << x << endl;
cout << "y aus dem Skript: " << y << endl;
printf("Ergebnis von multi x * y: %d\n", z);
return z;
}
void print(string &msg)
{
printf("%s", msg.c_str());
}
int _tmain(int argc, _TCHAR* argv[])
{
int r;
int c = 42;
asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
RegisterStdString(engine);
// pass function print to angelscript
r = engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); assert(r >= 0);
// pass function multi to angelscript
r = engine->RegisterGlobalFunction("int multi(int, int)", asFUNCTION(multi), asCALL_CDECL); assert(r >= 0);
// pass variable c to angelscript
r = engine->RegisterGlobalProperty("int c", &c); assert(r >= 0);
FILE *f = fopen("test.as", "rb");
fseek(f, 0, SEEK_END);
int len = ftell(f);
fseek(f, 0, SEEK_SET);
string script;
script.resize(len);
fread(&script[0], len, 1, f);
fclose(f);
mod->AddScriptSection("script", &script[0], len);
mod->Build();
asIScriptContext *ctx = engine->CreateContext();
// get function add from angelscript
asIScriptFunction *func = engine->GetModule("test.as")->GetFunctionByDecl("int add(int, int)");
ctx->Prepare(func);
ctx->SetArgDWord(0, 7);
ctx->SetArgDWord(1, 20);
if (ctx->Execute() == asEXECUTION_FINISHED)
{
asDWORD returnValue = ctx->GetReturnDWord();
cout << "Result of a + b is: " << returnValue << endl;
}
ctx->Release();
engine->Release();
return 0;
}
Here is my output when I run the code that you posted after making a few small modifications.
https://gyazo.com/cb264842efa76d153f9f5c0f962b391d
Here is the code after adding the small changes, I will explain what I added after.
All I had to change is how I built the module since you did not post how you created the module. If you copy and paste what I have it worked perfectly
Also now that I had the module pointer I could use that directly when getting the function by declaration
The way you defined the multi function was correct and how it is supposed to be done. I'm not sure exactly where your issue is but my guess it was how you created the module and that maybe you loaded it by the wrong name. I hope that helps!