Advertisement

Linking to C librarys in lua

Started by October 21, 2004 11:31 PM
2 comments, last by Fibonacci One 19 years, 10 months ago
Hello, I'm trying to learn how to write a function in C, compiling/linking it as a shared object, then calling said function in Lua. I can get it to work just fine if I do not pass any parameters into the C function, but as soon as I try to send something I get some weird results. here are some code samples: I use --> to indicate what the output of a statement is in lua

// In the C file (linking.c)
void hw(double temp)
{
    printf("Hello %f.\n", temp);
}


// in the lua file (linking.lua)
hello = loadlib("/usr/LUAcode/linking/linking.so", "hw")

print(hello) -->function: 0x806a318
hello(1.0) --> Hello 5.954010
hello(3.14159265) -->Hello 5.954010


The commands I use to compile Linking.c are: gcc -fPIC -c linking.c ld -shared -o linking.so linking.o I get 5.954010 every time I run the program. Does anyone reconize what I'm doing wrong? Thanks in advance
Yes. Hello function is called like a standard Lua function, so the first and the only argument must be a Lua state. It gives you the pointer to the state, but you treat it as a float!

The best thing here would be to read Lua manual, describing exact rules for exporting C functions. The function returned by dynamic library loader is supposed to open your shared library - the C code of it should register all the functions your library has.
Society's never gonna make any progress until we all learn to pretend to like each other.
Advertisement
I'm not sure how that is even working.

In order to call a C function from lua it needs to return a const int and accept a lua state as a parameter.

The parameters to the function call get pushed onto the stack, and you must remove them from the stack to get them.

Return values get pushed back onto the stack, the return being the number of variables being returned.
Ahh, it seems I was wrong to think it'd work like some other languages. Thanks for your help, I know where to look now.

This topic is closed to new replies.

Advertisement