gpt4 book ai didi

c# - pinvoke 返回一个 float

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:22 24 4
gpt4 key购买 nike

已经为此工作了几个小时,无法让它工作:(

下面的代码给出了异常“试图读取或写入 protected 内存。这通常表明其他内存已损坏。” 已修复,请参阅下面的更新

但是当我将返回类型更改为 int 并返回一个 int 值时,它起作用了。如何让它返回一个float值?谢谢。

vs2012

C++代码

extern "C"  __declspec(dllexport)
float compute_similarity()
{
return 1.01;
}

C#代码

[DllImport("demo.exe", EntryPoint = "compute_similarity", CallingConvention =  CallingConvention.Cdecl)]
public static extern float compute_similarity();

public void Get()
{
float x = compute_similarity(); // here returns random value
}

=====================================

更新

请参阅下面 David 的评论,问题是 c# 项目的目标是 x64 而 c++ 的目标是 Win32。将 c# 项目更改为目标到 x86 后,异常消失了。

但是来自 c# 的调用返回一些随机值而不是预期的 1.01

最佳答案

我认为你的问题是你的函数是在可执行文件而不是 DLL 中声明的。将您的 native 代码转换为库项目并编译 DLL。

您的代码将调用 LoadLibrary 并传递文件名 demo.exedocumentation对于 LoadLibrary 说:

LoadLibrary can also be used to load other executable modules. For example, the function can specify an .exe file to get a handle that can be used in FindResource or LoadResource. However, do not use LoadLibrary to run an .exe file. Instead, use the CreateProcess function.

因此您的代码正在执行您被告知不要执行的操作。对 LoadLibrary 的调用将会成功。对 GetProcAddress 的后续调用将成功。但是您加载的模块不适合执行代码。

关于c# - pinvoke 返回一个 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19242514/

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