gpt4 book ai didi

c# - 关于用 C++ 编写 CoreCLR 主机的文档

转载 作者:行者123 更新时间:2023-11-28 04:58:48 28 4
gpt4 key购买 nike

我正在用 C++ 编写 CoreCLR 主机。

我已经成功地从 C++ 中调用了一个 C# 函数: https://learn.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting

阅读该文档:

Another option, if ExecuteAssembly doesn't meet your host's needs, is to use CreateDelegate to create a function pointer to a static managed method. This requires the host to know the signature of the method it is calling into (in order to create the function pointer type) but allows hosts the flexibility to invoke code other than an assembly's entry point.

给定一个 C# 函数,我如何“创建 C++ 函数指针类型”

例如,对于这样的函数:

public static int withParams(int aNumber, string[] args)

是否有一些编码/解码规则,我如何将对象或数组作为参数?

是否有用于在 C++ 代码中嵌入 coreclr 的体面的官方文档?

我寻找这样的东西(但对于 coreclr): http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

最佳答案

我认为文档包含您需要的代码。

void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
domainId,
L"HW, Version=1.0.0.0, Culture=neutral", // Target managed assembly
L"ConsoleApplication.Program", // Target managed type
L"Main", // Target entry point (static method)
(INT_PTR*)&pfnDelegate);

((MainMethodFp*)pfnDelegate)(NULL);

我在 dotnet 核心 dll 中创建了一个类,并能够从 cpp 中调用它,如下所示。

void *pfnDelegate = NULL;
hr = runtimeHost->CreateDelegate(
domainId,
L"SampleAppCore", // Target managed assembly
L"SampleAppCore.Start", // Target managed type
L"Run", // Target entry point (static method)
(INT_PTR*)&pfnDelegate);
if (FAILED(hr))
{
printf("ERROR - Failed to execute %s.\nError code:%x\n", targetApp, hr);
return -1;
}


char* hello = "hello ";

((MainMethodFp*)pfnDelegate)(hello);

委托(delegate)的格式

typedef void (STDMETHODCALLTYPE MainMethodFp)(char* args);

核心类(class)

using System;
namespace SampleAppCore
{

public static class Start{

public static void Run(string input){

Console.WriteLine(input);
}

}
}

关于c# - 关于用 C++ 编写 CoreCLR 主机的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46574229/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com