从本地c++中反向PInvoke
Reverse PInvoke from native C++
我正在尝试从一个非托管的c++应用程序从c# DLL调用一个函数。
在网上搜索了几个小时之后,我发现我有几个选择。
我可以使用COM, DllExport
,或者对委托使用反向的PInvoke。最后一个听起来最吸引我,所以在搜索了so之后,我在这里结束了。
它指出本文展示了如何使用反向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, int count, 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", 0, 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:\temp\test.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();
}
相关文章:
- 我无法从 C# 获取 PInvoke 的输入参数以C++ DLL 以用作 IntPtr 的输出
- 在Mono-Pinvoke中尝试使用本机C++时未定义的符号
- 如何修复"方法的类型与 PInvoke 不兼容"
- C++互操作(隐式 PInvoke)的限制
- PINVOKE字节阵列从C 到C#
- 第二个值在 pinvoke 期间未传递给C++函数
- 将带有结构字段的结构从C 返回到C#PINVOKE
- 从 C# 到通过 PInvoke C++的简单结构中的垃圾数据
- 带有指针到指针参数的 PInvoke 函数
- 如何在C#中PInvoke另一个结构中的结构数组
- 无法为extern c int _clrcall生成pinvoke ..呼叫元数据中缺少的约定
- C#调用C 第三方DLL(无源)提出异常 - 不兼容PinVoke
- PInvoke "Attempted to read or write protected memory"
- AOT问题,消息"正在Xamarin iOS上尝试使用Pinvoke JIT编译方法"
- 是否更正PInvoke签名以使用带有C#保留内存的嵌套结构
- C# PInvoke - 返回 char* 和引用 char* 参数的函数
- 如何使用PINVOKE将图像从C或C 发送到C#
- Pinvoke阵列编组失败
- pinvoke c function - System.BadImageFormatException
- 使用PINVOKE编组LPWSTR的C风格数组,以托管字符串[]