对于接下来冗长的介绍,我们深表歉意。我需要比我更了解 P/Invoke 内部结构的人的见解。
以下是我如何将包含函数指针的结构从 C 编码到 C#。我想知道这是否是最干净和/或最有效的方式。
我正在与一个用 C 编码的 native DLL 交互,它提供以下入口点:
void* getInterface(int id);
您必须传递 getInterface(int) 以下枚举值之一:
enum INTERFACES
{
FOO,
BAR
};
它返回一个指向包含函数指针的结构的指针,例如:
typedef struct IFOO
{
void (*method1)(void* self, int a, float b);
void (*method2)(void* self, int a, float b, int c);
} IFoo;
下面是如何在 C 中使用它:
IFoo* interface = (IFoo*)getInterface(FOO);
interface->method1(obj, 0, 1.0f); // where obj is an instance of an object
// implementing the IFoo interface.
在 C# 中,我有一个 Library 类,它使用 P/Invoke 映射 getInterface(int) 入口点。
class Library
{
[DllImport("MyDLL"), EntryPoint="getInterface", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr GetInterface(int id);
};
然后我定义:
struct IFoo
{
public M1 method1;
public M2 method2;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void M1(IntPtr self, int a, float b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void M2(IntPtr self, int a, float b, int c);
}
我是这样使用它的:
IntPtr address = Library.GetInterface((int)Interfaces.FOO);
IFoo i = (IFoo)Marshal.PtrToStructure(address, typeof(IFoo));
i.method1(obj, 0, 1.0f): // where obj is an instance of an object
// implementing the IFoo interface.
我有以下问题:
映射整个结构是否比使用 Marshal.GetDelegateForFunctionPointer() 映射结构内部的单个指针效率低?
因为我基本上不需要接口(interface)公开的所有方法,所以我可以这样做(经过测试和工作):
unsafe
{
IntPtr address = Library.GetInterface(id);
IntPtr m2address = new IntPtr(((void**)address.toPointer())[1]);
M2 method2 = (M2)Marshal.GetDelegateForFunctionPointer(m2address, typeof(M2));
method2(obj, 0, 1.0f, 1);
}
当使用 Marshal.PtrToStructure() 一次映射整个结构时,有没有比我描述的更简洁的方法?我的意思是比必须为每个方法等定义委托(delegate)类型更简洁?
编辑:为了清楚和完整起见,在上面的代码片段中,obj 是使用 void* createObject(int type) 入口点获得的实例。
EDIT2:方法 1) 的一个优点是 Marshal.GetDelegateForFunctionPointer() 仅从 .NET Framework 2.0 开始可用。但是,Marshal.PrtToStructure() 始终可用。也就是说,我不确定现在是否值得确保 1.0 的兼容性。
EDIT3:我尝试使用 Reflector 检查生成的代码但它并没有提供太多信息,因为所有有趣的细节都是在辅助函数中完成的,例如 PtrToStructureHelper 并且没有公开。然后,即使我可以看到框架内部做了什么,运行时也有机会优化掉一些东西,我不知 Prop 体是什么、为什么以及什么时候:)
但是,我对问题中描述的两种方法进行了基准测试。与 Marshal.GetDelegateForFunctionPointer() 方法相比,Marshal.PtrToStructure() 方法慢了大约 10%;一个包含所有不感兴趣的函数的 IntPtr 的结构。
我还将 Marshal.GetDelegateForFunctionPointer() 与我自己的滚动编码器进行了比较:我对齐表示调用堆栈的 struct,将其固定在内存中,将其地址传递给我使用在 asm 中编码的蹦床的 native 端,以便调用函数使用内存区域作为其参数堆栈(这是可能的,因为 cdecl x86 调用约定传递堆栈上的所有函数参数) .时间是等效的。
最佳答案
这是我要开始的。
用法:
IFoo foo = UnsafeNativeMethods.GetFooInterface();
foo.Method1(0, 1.0f);
实现:
internal interface IFoo
{
void Method1(int a, float b);
void Method2(int a, float b, int c);
}
internal static class UnsafeNativeMethods
{
public static IFoo GetFooInterface()
{
IntPtr self = GetInterface(InterfaceType.Foo);
NativeFoo nativeFoo = (NativeFoo)Marshal.PtrToStructure(self, typeof(NativeFoo));
return new NativeFooWrapper(self, nativeFoo.Method1, nativeFoo.Method2);
}
[DllImport("mydll.dll", EntryPoint = "getInterface", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr GetInterface(InterfaceType id);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void Method1Delegate(IntPtr self, int a, float b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void Method2Delegate(IntPtr self, int a, float b, int c);
private enum InterfaceType
{
Foo,
Bar
}
private struct NativeFoo
{
public Method1Delegate Method1;
public Method2Delegate Method2;
}
private sealed class NativeFooWrapper : IFoo
{
private IntPtr _self;
private Method1Delegate _method1;
private Method2Delegate _method2;
public NativeFooWrapper(IntPtr self, Method1Delegate method1, Method2Delegate method2)
{
this._self = self;
this._method1 = method1;
this._method2 = method2;
}
public void Method1(int a, float b)
{
_method1(_self, a, b);
}
public void Method2(int a, float b, int c)
{
_method2(_self, a, b, c);
}
}
}
关于C# P/调用 : Marshalling structures containing function pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1969049/
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时
如何找到调用此方法的位置?defto_xml(options={})binding.pryoptions=options.to_hifoptions&&options.respond_to?(:to_h)serializable_hash(options).to_xml(options)end 最佳答案 键入caller。这将返回当前调用堆栈。文档:Kernel#caller.例子[0]%rspecspec10/16|===================================================62=====
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"
我正在写一篇关于在Ruby中几乎一切都是对象的博客文章,我试图通过以下示例来展示这一点:classCoolBeansattr_accessor:beansdefinitialize@bean=[]enddefcount_beans@beans.countendend所以从类中我们可以看出它有4个方法(当然,除非我错了):它可以在创建新实例时初始化一个默认的空bean数组它可以计算它有多少个bean它可以读取它有多少个bean(通过attr_accessor)它可以向空数组写入(或添加)更多bean(也通过attr_accessor)但是,当我询问类本身它有哪些实例方法时,我没有看到默认
我写了一个非常简单的rake任务来尝试找到这个问题的根源。namespace:foodotaskbar::environmentdoputs'RUNNING'endend当在控制台中执行rakefoo:bar时,输出为:RUNNINGRUNNING当我执行任何rake任务时会发生这种情况。有没有人遇到过这样的事情?编辑上面的rake任务就是写在那个.rake文件中的所有内容。这是当前正在使用的Rakefile。requireFile.expand_path('../config/application',__FILE__)OurApp::Application.load_tasks这里