加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从本机C反转PInvoke

发布时间:2020-12-15 04:16:56 所属栏目:百科 来源:网络整理
导读:我目前正在尝试从非托管C应用程序中调用C#DLL中的函数. 在网上搜索了几个小时后,我发现我有几个选择. 我可以使用COM,DllExport,或使用反向PInvoke与委托.最后听起来最吸引我,所以在搜索之后我结束了here. 它声明该文章展示了如何使用反向PInvoke,但看起来C#
我目前正在尝试从非托管C应用程序中调用C#DLL中的函数.

在网上搜索了几个小时后,我发现我有几个选择.

我可以使用COM,DllExport,或使用反向PInvoke与委托.最后听起来最吸引我,所以在搜索之后我结束了here.

它声明该文章展示了如何使用反向PInvoke,但看起来C#代码必须首先导入C Dll,然后才能使用它.

我需要能够使用C来调用我的C#Dll函数,而无需先运行C#应用程序.

也许逆转的PInvoke是不这样做的方式,但我很没有经验,当涉及到低层次的东西,所以就如何做到这一点的任何指针或建议将是巨大的.

链接中的代码是

C#

using System.Runtime.InteropServices;

public class foo    
{    
    public delegate void callback(string str);

    public static void callee(string str)    
    {    
        System.Console.WriteLine("Managed: " +str);    
    }

    public static int Main()    
    {    
        caller("Hello World!",10,new callback(foo.callee));    
        return 0;    
    }

    [DllImport("nat.dll",CallingConvention=CallingConvention.StdCall)]    
    public static extern void caller(string str,int count,callback call);    
}

C

#include <stdio.h>    
#include <string.h>

typedef void (__stdcall *callback)(wchar_t * str);    
extern "C" __declspec(dllexport) void __stdcall caller(wchar_t * input,callback call)    
{    
    for(int i = 0; i < count; i++)    
    {    
        call(input);    
    }    
}

解决方法

嗯,只需启动你自己的CLR主机并运行你需要的东西:
#include <mscoree.h>
#include <stdio.h>
#pragma comment(lib,"mscoree.lib") 

void Bootstrap()
{
    ICLRRuntimeHost *pHost = NULL;
    HRESULT hr = CorBindToRuntimeEx(L"v4.0.30319",L"wks",CLSID_CLRRuntimeHost,IID_ICLRRuntimeHost,(PVOID*)&pHost);
    pHost->Start();
    printf("HRESULT:%xn",hr);

    // target method MUST be static int method(string arg)
    DWORD dwRet = 0;
    hr = pHost->ExecuteInDefaultAppDomain(L"c:temptest.dll",L"Test.Hello",L"SayHello",L"Person!",&dwRet);
    printf("HRESULT:%xn",hr);

    hr = pHost->Stop();
    printf("HRESULT:%xn",hr);

    pHost->Release();
}

int main()
{
    Bootstrap();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读