Calling C dll from love2d

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
User avatar
pgimeno
Party member
Posts: 3657
Joined: Sun Oct 18, 2015 2:58 pm

Re: Calling C dll from love2d

Post by pgimeno »

I remember someone having a similar problem, here: https://love2d.org/forums/viewtopic.php?f=4&t=88104

Maybe this helps them.
User avatar
HDPLocust
Citizen
Posts: 65
Joined: Thu Feb 19, 2015 10:56 pm
Location: Swamp
Contact:

Re: Calling C dll from love2d

Post by HDPLocust »

On windows you should use __declspec(dllexport).
Minimal crossplatfom library looks like this.

Code: Select all

#include "lua/lua.h"
#include "lua/lauxlib.h"
 
int lua_summ(lua_State *L){
    double a = luaL_checknumber(L, 1); /* get first arg */
    double b = luaL_checknumber(L, 2); /* get second arg */
    lua_pushnumber(L, a + b);          /* returning value to lua */
    return 1;                          /* count of args returned to lua */
}
 
#if defined(_WIN32) || defined(_WIN64) /* windows compat */
__declspec(dllexport)
#endif
int luaopen_mylib(lua_State *L) {       /* compile it to mylib.dll or libmylib.so */
    lua_newtable(L);                    /* create table */
        lua_pushstring(L, "summ");      /* push "summ" as key*/
        lua_pushcfunction(L, lua_summ); /* push lua_summ as value*/
        lua_rawset(L, -3);              /* assign key and value to this table (it gone from stack, but not table) */
 
    return 1; /* return table to lua */
}
Here no usage of lua_reg, but nothing global is created.

So usage on lua side is:

Code: Select all

local lib = require'mylib'
print(lib.summ(10, 20)) --> 30
Also you should to compile it to target lua version and platform (using luajit lua51.lib and same as your love x86_32/x86_64 target)
Science and violence
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests