Linking to C librarys in lua

This topic is 5108 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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)

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

Share on other sites
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.

Share on other sites
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.

Share on other sites
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.

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5

• 13
• 19
• 14
• 9
• 9
• Forum Statistics

• Total Topics
632930
• Total Posts
3009289
• Who's Online (See full list)

There are no registered users currently online

×

Important Information

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!