Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a lua string to a C char*?

Tags:

c

lua

ffi

luajit

I've used the luajit ffi library to wrap a C library that contains a function to draw text on a ppm file:

void drawText(frameBuffer *fb, int px, int py, char* text, pixel color) 

When I try to call it from lua using a string I get this error bad argument #4 to 'drawText' (cannot convert 'string' to 'char *'). It doesn't look like the lua string library has anything to convert entire strings to byte arrays or anything that I could manipulate sufficiently.

Any tips on how I could do this on the lua side without modifying the C code?

like image 529
BarFooBar Avatar asked Nov 02 '15 19:11

BarFooBar


People also ask

What is Lua Lua string?

Lua - Strings. String is a sequence of characters as well as control characters like form feed. An example for the above three forms are shown below. When we run the above program, we will get the following output. Escape sequence characters are used in string to change the normal interpretation of characters.

How to convert a decimal to a character in Lua?

string.char () function in Lua programming Lua Server Side Programming Programming There are so many scenarios where you might want to convert a decimal value into a character representation. The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table.

What is the use of the escape sequence in Lua programming?

Escape sequence characters are used in string to change the normal interpretation of characters. For example, to print double inverted commas (""), we have used " in the above example. The escape sequence and its use is listed below in the table. Lua supports string to manipulate strings −.

What is a string in C++?

String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes − An example for the above three forms are shown below. When we run the above program, we will get the following output.


1 Answers

You cannot pass a Lua string to a ffi function that expects a char* directly. You need to convert the Lua string to a char* first. To do so, create a new C string variable with ffi.new and after that copy the content of your Lua string variable to this new C string variable. For instance:

local text = "text"
-- +1 to account for zero-terminator
local c_str = ffi.new("char[?]", #text + 1)
ffi.copy(c_str, text)
lib.drawText(fb, px, py, c_str, color)
like image 135
Diego Pino Avatar answered Sep 23 '22 19:09

Diego Pino