我玩了这个dotnet hosting example的代码,遇到了一些问题.

这就是我如何得到函数指针:

component_entry_point_fn function = nullptr;
    int rc = functionPointer(
      dllPath.c_str(),
      dotnetType.c_str(),
      methodName.c_str(),
      nullptr,
      nullptr,
      (void**)&function);

然后我给它打了电话:

struct test {
      const char* str = "from host!";
      int i = 1;
    } testArgs;

function(&testArgs, sizeof(testArgs));

而且它运行得很好.输出:

Hello, world! from Lib [count: 1]
-- message: from host!
-- number: 1
Hello again, world! from Lib [count: 2]
-- message: from host!
-- number: 1

但当我try 将参数作为元组传递时:

std::tuple<FunctionArgs...> argsTuple = std::make_tuple(args...);
function(&argsTuple, sizeof(argsTuple));

我知道了

Hello, world! from Lib [count: 1]
Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.SpanHelpers.IndexOfNullByte(Byte*)
   at System.Runtime.InteropServices.Marshal.PtrToStringUTF8(IntPtr)
   at Scripts.Lib.PrintLibArgs(LibArgs)
   at Scripts.Lib.HelloAgain(IntPtr, Int32)

C#端的代码与上面链接中的示例相同. Another important fact is that everything works without errors on Arm MacOS. The error appears on Linux x86_64. The compiler is the same everywhere: clang.

struct 和元组的sizeof是相同的—16字节. 已try 添加对齐方式:

alignas(16) std::tuple<FunctionArgs...>
      argsTuple = std::make_tuple(args...);

推荐答案

x64架构上的所有MSVC和gcc和clang似乎都交换了内存https://godbolt.org/z/PW55PfGGE中元组元素的顺序,但这是一个实现细节,不是你可以依赖于代码的东西,正如你看到的,这可能不是ARM架构的情况.

你不应该将C++元组传递给C接口,它们没有任何布局要求.

Csharp相关问答推荐

System.Data.SQLite:判断SQLite数据库是否为空(任何表中至少有一行)

Plotly.NET访问互联网时出现异常

Dapper是否可以自动扩展类成员

ListaryImportProperty的默认DllImportSearchPathsProperty行为

在Dapper中使用IasyncEum重写GetAsyncEum方法

为什么EF Core 6会针对null验证Count(*)?

如何使用XmlSerializer反序列化字符串数组?

在具有主构造函数的类中初始化属性时出现警告

如何在没有额外副本的情况下将存储在IntPtr下的原始图像数据写入WinUI3中的Image控件?

Amazon SP-API确认发货不设置&Quot;递送服务

MigraDoc文档

TeamsBot SendActivityActivityTypes与ActivityTypes同步.键入不再起作用

当前代码Cosmos DB 3.37.1:PartitionKey key key mismatch exception

如何管理Azure认证客户端响应和证书 fingerprint

BFF到具有AAD/Entra ID B2C的内部API(.NET/ASP.NET核心/标识.Web)

.NET 6:如何防止系统生成的日志(log)?

如何实现有条件的自定义Json转换器隐藏属性

RavenDb:为什么在字符串==空的情况下过滤会过滤得太多?

ASP.NET核心中的授权,如何在DbContext启动之前提供租用ID

如何为控制器PUT操作绑定对象数组