lua cinvoke

tolua笔记《04》- Lua Function调用 在前面几篇中已经介绍了C#如何调用Lua脚本,本篇中我们进一步通过**03_CallLuaFunction**s示例进一步了解Lua脚本中的Function是如何调用的。 演示效果 示例代码 using UnityEngine; using System.Collections; using LuaInterface; using System; public class ... 阅读详情
 /Invoke

Easily call C from any language.

General Info

The C/Invoke Lua Binding uses the new Lua module system, so to use C/Invoke in your Lua programs, load the module like so:

require("cinvoke_lua")

To call C functions easily without writing a Lua module, declare a new instance of the clibrary class to load a dynamic library. The clibrary instance has methods which allow you to load functions and variables, similar to dlopen() and dlsym() on UNIX, except that you also specify the types of the parameters and the return value:

libc = clibrary.new("libc.so.6")

getpass = libc:get_function(Cstring, "getpass", Cstring)

Here we load libc.so.6 (you will have to adjust this for operating systems other than GNU/Linux) and then call get_function on the returned instance. We pass arguments to get_function to specify a function named 'getpass' which returns a type Cstring (essentially a const char *) and takes a single argument of type Cstring. get_function returns a callable Lua function object, which we assign to a variable also named getpass. This function is now usable:

pass = getpass("Enter a password: ")
print("You entered " .. pass)

Thus we have now integrated the previously unavailable getpass() function into Lua, without writing any C!

The clibrary class also has a method to create a callback, which is analogous to a C function pointer, and which allows C libraries to call Lua functions. There is also a cstructure class for defining struct types, as well as a cinv class which provides global helper methods to assist with data marshalling.

How Types Are Marshaled

There are two sorts of types in cinvoke_lua, built-in and user-defined. The list of built-in types is in the class reference below, and includes most of the basic types from C (integers, floating point values, etc.). These are marshaled to and from Lua as one would generally expect. Values of type Cchar are marshaled as Lua strings with length 1, not as their byte (integer) value.

Another built-in type is Cstring, which as mentioned earlier is useful for marshaling constant strings. Note we must emphasize the "constant"; Lua strings are immutable and passing them to a function which writes to their memory is extremely bad. You can also have functions which return string values, in which case the value returned is truncated at the first /0 character.

This limitation on returning string data as well as almost any other limitation can be overcome with the use of arrays and pointers. To declare an array type, use the cinv.array function on a non-array type. Arrays in Lua are represented in the normal manner with a table:

strcpy = libc:get_function(Cptr, "strcpy", cinv.array(Cchar), Cstring);

buf = { "a", "b", "c", "d" }

strcpy(buf, "ef")

-- buf is now { "e", "f", "/0", "d" }

As you can see, with an array you can have values written back to Lua via parameters. This function also uses the Cptr built-in type as the return type. A ptr is an opaque object (actually represented by a string) which can be used to send or receive raw pointer values to C. They can then be used with functions such as cinv.ptr_to_array and cinv.ptr_to_struct to marshal values which would otherwise be impossible for C/Invoke to determine (for example, returning an array directly from a function is not allowed because C/Invoke doesn't know the length of the returned value). Using ptrs also allows you to capture data returned by functions like malloc() and then later return their pointer values back to the C library.

In general, you can use arrays whenever you wish to pass a pointer value as a parameter (in C, an array with one element and a pointer are essentially the same). Ptrs are useful for return values as well as situations where you must hand-marshal parameters. If you wish to pass a NULL value to a function, C/Invoke allows you to pass a nil value for an array or ptr. Ptr params will also accept the integer 0 as a NULL value.

The cstructure class contains one method to create a new structure type. For example, to create the equivalent of the following C definition:

struct Foo {
	int i1;
	short s1;
};

void myfunc(struct Foo *f);

One would do the following:

Foo = cstructure.new(
	Cint, "i1",
	Cshort, "s1"
)
myfunc = mylib:get_function(Cvoid, "myfunc", cinv.array(Foo))

And to use them:

s = { i1 = 1, s1 = 2 }
myfunc({s}) -- note extra level of indirection to pass in an array

Struct types cannot be passed by value, only in arrays and marshaled by hand with pointers.

The final built-in type is Ccallback, which represents all C function pointers. To create an instance of a callback, use the clibrary:new_callback method, passing the Lua function you would like to call instead of the name of the function to load as in get_function (this method is a member of clibrary because it uses the calling convention that the library was declared with):

C:

void myfunc(void (*cb)(int)) {
	cb(1);
}

Lua:

function lua_cb(i)
	print(i)
end

myfunc = mylib:get_function(Cvoid, "myfunc", Ccallback);
cbobj = mylib:new_callback(Cvoid, lua_cb, Cint);

myfunc(cbobj) -- prints "1"

A warning: you should only use callbacks in situations where all calls to the callback are done inside the called function. This will ensure that the Lua context being called back to is still active. It is especially dangerous for a C function to keep a reference to a callback and then call it later in another thread; the Lua object holding the callback may have been garbage collected and the Lua interpreter is not thread safe.

Class Reference

Built-in Types

Cvoid

A placeholder to declare a function with no return value.

Cchar

The char type is always 1 byte wide. This type is marshaled as a Lua string with length 1.

Cshort

The short type is marshaled as an integer.

Cint

The int type is marshaled as an integer.

Clong

The long type is marshaled as an integer.

Clonglong

The long long integer type is available on some platforms; it is typically used to represent an 8-byte integer on 32-bit machines.

Cint16

This integer type is aliased to the type which is two bytes wide on the current platform.

Cint32

This integer type is aliased to the type which is four bytes wide on the current platform.

Cint64

This integer type is aliased to the type which is eight bytes wide on the current platform.

Cfloat

C floating point values are marshaled as a Lua number.

Cdouble

C double-precision floating point values are marshaled as a Lua member.

Cstring

The string type allows Lua strings to be passed to functions accepting a const char *. Do not use this type for mutable arrays or to return a value from a function which is not /0 terminated.

Cptr

This type represents a Pointer value, however large that may be on the current platform. Values of this type should only be either returned from a C function, or the value nil or the integer 0. You can pass values of this type to many members of the cinv class to marshal values which would otherwise be difficult to for C/Invoke to process.

Ccallback

Represents any C function pointer, regardless of the prototype. Valid values are generated (with prototype information) by the clibrary:new_callback method.

Classes

cinv

array(type)

Returns a new type representing a C array (passed by reference) of the specified type. The passed type is not modified.

chararray_to_string(arr[, len])

Converts a Lua array (a table with integer keys) of values of type Cchar to a Lua string. If len is not specified, the length is determined by the length of the array.

string_to_chararray(str[, includenil])

Converts a Lua string to a Lua array (a table with integer keys) of values of type Cchar. If includenil is true, then the last element of the array will be a /0 byte value.

ptr_to_string(ptr[, len])

Converts a ptr value (presumably pointing to an array of chars) to a Lua string. If len is not specified, conversion continues up until the first /0 character.

ptr_to_array(ptr, type, len)

Converts a ptr value to a Lua array of values of the specified type. This method provides a way to unmarshal return values consisting of pointers to structures.

ptr_to_struct(ptr, type)

Converts a ptr value to a Lua table, with the keys and values set to the fields of the specified structure type. Essentially equivalent to cinv.ptr_to_array(ptr, type, 1)[1].

ptr_to_callback(ptr)

Converts a ptr value to a value suitable for passing as a Ccallback. Useful for C functions which return function pointers.

callback_to_ptr(cb)

Converts a C/Invoke callback returned by clibrary:new_callback to a raw ptr value. The returned ptr points to managed memory inside the Lua interpreter, and the same cautions apply when using it as when passing callback values to a function.

sizeof(type)

Returns the number of bytes needed to hold the given type.

clibrary

new(libname[, callingconv])

Opens a C shared library. Libname is a platform-specific string containing the name of the library to load, i.e. "libc.so" or "kernel32.dll". callingconv specifies a calling convention to use. Currently supported are "cdecl", "stdcall", "fastcall", and "default". If callingconv is not specified then the default is used. Platforms other than Microsoft Windows typically only use the default calling convention. On Windows, stdcall should be used for all Win32 API functions.

dispose(self)

Unloads the given library instance from memory.

get_function(self, rettype, name, ...)

Creates a new C function object in the given library, and returns a callable Lua function value. If the function returns void, specify Cvoid for rettype, otherwise specify the correct return type. The name parameter is the name of the symbol in the shared libary to load. If the function takes parameters, pass the types of the parameters in order after the name. Functions with variable argument lists are not supported. For other limitations, see the documentation on specific types.

new_callback(self, rettype, cbfunc, ...)

Creates a callback object which can be passed as a function pointer to a C function. The arguments are the same as for get_function, except that instead of a symbol name, a Lua function is passed. This function will then get called when the C code calls through the function pointer. Because C/Invoke cannot control the values being passed into and returned from the callbacks, there are additional constraints on the types of arguments a callback can take; in particular, arrays are not allowed as arguments.

It is highly reccomended to only use callbacks in circumstances where the passed function pointer is called within the context of the C function, and nowhere else. Storing a pointer to a Lua callback and calling it later in the program execution could lead to undefined behavior.

tie_init(self, type, name)

Creates an entry in the library instance for a tied variable, i.e. a symbol in a shared library which points to a global C variable. Only basic types (not strings, structs, callbacks, etc.) can be tied.

tie_get(self, name)

Returns the value of a tied C variable as a Lua object.

tie_set(self, name, value)

Sets the value of a tied C variable.

cstructure

new(type, name[, type, name ...])

Creates a new structure type. Each pair of arguments to this function adds a member to the structure. Once a function with the returned type is declared, a table value with the given name values as keys can be used to represent an instance of this structure. Structures cannot be passed to C functions by value; they must be passed in an array. Structures cannot contain arrays or callbacks, but they can contain embedded in-line structure types. For example, the following C definition:

struct Inner {
	int u;
	int v;
};

struct Outer {
	struct Inner in;
	float out;
};

Can be represented in Lua as shown:

Inner = cstructure.new(
	Cint, "u",
	Cint, "v"
)
Outer = cstructure.new(
	Inner, "in",
	Cfloat, "out"
)
Unity C#与Xlua的交互 C#调用Lua CSharpCallLua 最近学习XLua,看了下官方的文档。对于我这样的小菜鸡而言需要知道的知识点还是蛮多的,就做个笔记,其实差不多等于把文档里面的知识ctrl C ctrl V一遍。正在准备学习这块的小伙伴们可以多看看官方给的文档。下面是自己的一个GitHub XLua Demo 地址。里面也存放了文档(XLuaDocs文件夹中)这篇主要记录记录C#与XLua的相互交互,即C#如何访问调用Lua的属性方法和Lua如何调... 阅读详情

相关推荐

Obsidian从零搭建:可验证、可回溯、可演进的知识库工具链

个人知识库不是开箱即用的软件,而是基于Markdown内核构建的可演进系统。其核心原理在于分离‘稳定内核’与‘可插拔扩展’:Obsidian原生支持双链、嵌入、Frontmatter等基础能力,构成不可降级的知识骨架;而Dataview、Templater等插件则作为可验证、可回溯的增强层,需通过三问验证(解决痛点?有原生替代?失效可降级?)方可引入。这种设计赋予知识库技术价值——抗版本升级、跨平台兼容、离线可用,并支撑技术文档管理、项目复盘、读书笔记等真实场景。当面对computer use插件不可用或h

weixin_30660027的博客 687

Java与lua互相调用简单教程

点击上方“芋道源码”,选择“设为星标”管她前浪,还是后浪?能浪的浪,才是好浪!每天 10:33更新文章,每天掉亿点点头发...源码精品专栏原创 | Java 2021超神之路,很肝~中文详细注释的开源项目RPC 框架 Dubbo 源码解析网络应用框架 Netty 源码解析消息中间件 RocketMQ 源码解析数据库中间件 Sharding-JDBC 和 MyCAT 源码解析作业调度中间件 E...

芋艿V 2393

小米万兆路由器里的Docker安装可道云(Kodexplorer)私有网盘

小米2022年12月份发布了万兆路由器,里面可以使用Docker。 今天尝试在小米的万兆路由器里安装[可道云](http://kodcloud.com/)(Kodexplorer)私有网盘。

engchina的专栏 1万+

排错“未能封送类型,因为嵌入数组实例的长度与布局中声明的长度不匹配”...

问题:在C#给C++传数组类型数据时报此错,相应英文信息为“Type could not be marshaled, because the length of an embed array doesn't not match the declared length in the layout” 原因1、声明的数组长度和实际的数组长度不一致,比如声明的数组长度为1000,实际数组里放了1000多...

weixin_30408309的博客 2918

整车 EOL下线 测试系统介绍

整车下线(EOL)测试专门针对整车进行设计开发,是车企将组装好的整车交付客户前的 最后一道检测工序。EOL 测试针对的是整车下线测试,不同于零部件下线,是整车级别的下线 测试,测试过程关系整车的每个零部件,其测试质量直接影响到整车的质量好坏。因此,整车EOL测试是整车下线必不可少的测试过程.

王小奎的博客 5517

java三角套利_三角对冲套利-EA原理全解析

它是两个直盘货币和一个交叉盘货币之间的相互对冲,交易员往往受到外界因素的影响无法严格执行造成亏损。该系统经过大量数据统计分析和严格的科学论证计算,并通过多年实盘交易验证可以达到稳定盈利。希望交易员严格按照交易规则执行。此策略利用交叉外汇对的市场价格与其合成价格的价差来实现套利,还以EUR/USD和GBP为例:1,我们关注三个外汇对:EUR/USD,GBP/USD,以及GBP/EUR2,计算GBP/...

weixin_29531897的博客 2423

腾讯XLua 03-CSharp Invoke Lua

using UnityEngine; using System.Collections; using XLua;public class MyInvokeLua : MonoBehaviour { //创建一个接口 用于生成 调用函数 [CSharpCallLua] //这是一个生成调用函数用的标签 生成CSharp调用Lua,加这标签 public interface I

.Vergil 技术博客 3293

基于YOLO11深度学习的糖尿病视网膜病变智能诊断系统【Python源码+Pyqt5界面+数据集+训练代码】

本文详细介绍如何利用YOLO11深度学习技术构建糖尿病视网膜病变智能诊断系统。项目提供完整的Python源码、PyQt5图形界面、标注数据集及训练代码,实现从图片、视频到摄像头的多模态病变检测,旨在辅助医疗筛查,提升诊断效率。

weixin_29089057的博客 281

学习lua结合unity遇到错误信息的解决方法

require "uiDefine" 报错信息:module 'uiDefine' not found: no fieldpackage.preload['uiDefine'] no such builtin lib'uiDefine' 解决方法: 在require "ui.uiDefine" 在基于lua根目录的下require全路径,例如Assets/Scripts/lua为根目录 static public class UnityCommonExtension { stati...

蛰伏--当你不够强大时,就不要放弃努力 2万+

Unity AR开发实战:从Vuforia图片识别到实体识别全流程解析

增强现实(AR)技术通过计算机视觉算法将虚拟信息叠加到现实世界,其核心原理在于对现实环境的感知与理解。在移动端AR开发中,图像识别与物体识别是实现虚实融合的关键技术,它们决定了虚拟内容能否准确、稳定地与现实对象对齐。Vuforia作为成熟的商业AR SDK,为开发者提供了从平面图像识别(Image Target)到三维实体识别(Model Target)的完整解决方案,极大降低了计算机视觉技术的应用门槛。在工程实践中,Vuforia通过封装复杂的特征提取与匹配算法,使开发者能够专注于交互设计与内容制作,广泛

weixin_30972263的博客 307

YOLOv11 改进 - C2PSA | C2PSA融合TSSA(Token Statistics Self-Attention)令牌统计自注意力,优化遮挡目标感知

本文介绍了Token Statistics Self-Attention(TSSA)机制,并将其集成到YOLOv11中。传统自注意力计算复杂度高,TSSA进行了范式转变,基于token统计特征实现高效注意力交互。它通过“算法展开”推导得出,以“最大编码率降低”为目标,实现特征学习。TSSA包含动态分组和低秩投影优化两步创新,具备线性复杂度。我们将TSSA代码集成到YOLOv11的C2PSA模块中。实验表明,改进后的YOLOv11在目标检测任务中表现良好,验证了TSSA机制的有效性。

魔改工程师的博客 674

Invoke函数的妙用

众所周知,invoke函数有两个重载方式 1 Invoke(methodName, time)经过多长时间后,调用该方法一次 在实际中,切换到游戏开始场景后,一般要等待几秒给玩家缓冲,然后再开始运行角色,可以使用这个方法 2 InvokeRepeating(methodName, time, repeatTime), 经过time时间后调用该方法,并且每过repeatTime再重新调用一次 第二...

超胆孤侠 1万+

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

xLua 与C#的交互

adfasdfadfC#脚本:namespace LuaInterfaceSolution { class Program { public string sre = "123"; public static int num =456; public string LuaTest( string str) { ...

Yuan_bowen的博客 898

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

lua_call

lua_call,执行压入栈中的函数,该函数可能是lua中的函数,也可能是C++中定义的函数,一般用于执行lua中定义的函数。void lua_call(lua_State *L,int args,int ret),其中L是当前栈,args是被执行函数中的参数,ret是被执行函数返回值。void lua_pcall(lua_State *L,int args,int ret,int error_f

木木三的专栏 5320

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

tolua

tolua.type返回一个 C++ 对象的类型描述字符串。local node = display.newNode()print(tolua.type(node))-- 输出 CCNode=========================================================================================tolua...

weixin_34163741的博客 263

关于LUA+Unity开发_toLua篇【一】

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34216107的博客 624

从零开始搭xlua框架(三)实现类似C#UnityEngine.MonoBehaviour.Invoke

之前一直在纠结lua里面没有invoke这个函数 很不方便 就一直在网上找lua中的延迟调用函数 发现根本就没有 我想要的答案 后来跑xlua的交流群里面去问了一下 终于有人给解决方案了 实际上很简单的一件事 只是自己有点死脑壳 想不通 解决方案: C#端实现 定时器 给lua调用就好了 C#端 using System; using System.Collections.Generi...

qq_43204246的博客 858

C# 关于Invoke(详解)

Control的Invoke一般用于解决跨线程访问的问题,比如你想操作一个按钮button,你就要用button.Invoke,你想操作一个文本label,你就要用label.Invoke.但是大家会发现很麻烦,如果我既然想操作button,又操作label,能不能写在一起呢?其实主窗体使一个Form,Form自然也是继承了Control的,所以Form也有Invoke的方法,如果你想省点事,就可以直接调用Form.Invoke,这就是常见的this.Invoke.为什么有的Invoke前面啥都没有?

这个人好有趣....hh 7万+

C#Invoke和BeginInvoke的用法转载至微雨夏凉

Invoke与BeginInvoke的区别

weixin_42609581的博客 1852

tolua框架学习(之三)

      第三个案例讲的是调用lua中的函数方法。核心方法就是luaState中的GetFunction()方法。该方法会先从funcMap这个字典中查找对应的方法对象,有的话,并且该方法仍然处于非游离状态(IsAlive),就会返回该方法,并且从GC列表中删除该方法。否者就会从funcMap中删除该方法对象。 否则,会通过PushLuaFunction方法获取对象。该方法同样也会先在fu...

Tong1993222的博客 1439

C#中Invoke的用法

在用.NET Framework框架的WinForm构建GUI程序界面时,如果要在控件的事件响应函数中改变控件的状态,例如:某个按钮上的文本原先叫“打开”,单击之后按钮上的文本显示“关闭”,初学者往往会想当然地这么写: void ButtonOnClick(object sender,EventArgs e) { button.Text="关闭"; } 这样的写法运行程序之后,可...

weixin_30919919的博客 3856

数组、指针、结构体的总结_吃鱼的小脸猫_新浪博客

一、结构体和数组的区别 1、定义一个结构体是为方便保存不同类型的数据,而不同类型的数据放在一个结构体中 2.定义数组也是为方便存储大量数据,但数据必须是同一类型 3、 结构体中也包括结构体数组和结构体指针,而结构体中的数组和指针与本身的数组和指针用法也相同,唯一不同就是结构体数组中保存的多种类型的数据 二、scanf和getchar的安全性 一般不使用scanf和getcha...

qq_42497694的博客 502
上一篇: 使用Lua进行面向对象编程,一种新的样式
下一篇: 用 lua 调用 Windows 的 API
skyremember
博客等级 码龄20年 205粉丝 484原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值