gpt4 book ai didi

c# - 尝试在 c# 中使用 dllimport 读取或写入 protected 内存

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:27:41 25 4
gpt4 key购买 nike

我的项目有问题:在 dll C++ 中:

    extern "C" __declspec(dllexport) int results(char* imgInput, void* tree)
{
struct kd_node* nodeTree = new(tree)kd_node ; // new kd_tree with data from memory address
...

...
int ret = atoi(retValueStr.c_str());
return ret;
}

extern "C" __declspec(dllexport) void* buildKDTree(char* folder)
{
struct kd_node* kd_root;
....

feature *LFData = listFeat.data();
kd_root = kdtree_build(LFData,listFeat.size());
void* address_kdtree = (void*)&kd_root; // get memory address of kd_tree
return address_kdtree;
}

我在 C# 中使用 dllimport:

[DllImport(@"kdtreeWithsift.dll", EntryPoint = "buildKDTree", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern void* buildKDTree(byte[] urlImage);


[DllImport(@"kdtreeWithsift.dll", EntryPoint = "results", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs(UnmanagedType.I4)]
public unsafe static extern int results(byte[] imgInput, void* tree);

static unsafe void Main()
{
string urlImg1 = "C:/Users../test img/1202001T1.jpg";
string urlImg = "C:/export_features";

try
{
IntPtr result;
int result1;
result1 = results(convertStringToByte(urlImg1), 5, buildKDTree(convertStringToByte(urlImg))); // this error
Console.WriteLine("results = %d",result1);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}

当我运行该程序时,该程序显示错误:尝试读取或写入 protected 内存。这通常表明其他内存已损坏

您知道什么错误以及如何解决?谢谢!

最佳答案

此处不需要convertStringToByte 方法。您可以告诉运行时将您的字符串编码为 char *。另外,我建议您让该方法返回一个 IntPtr,如下所示:

[DllImport(@"kdtreeWithsift.dll", EntryPoint = "buildKDTree",
CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr buildKDTree([MarshalAs(UnmanagedType.LPStr)]string urlImage);

[DllImport(@"kdtreeWithsift.dll", EntryPoint = "results",
CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs(UnmanagedType.I4)]
public static extern int results([MarshalAs(UnmanagedType.LPStr)]string imgInput, IntPtr tree);

然后你可以调用它:

IntPtr tree = buildKDTree(urlImg);
int result1 = results(urlImg, 50, tree);

Console.WriteLine("results = {0}",result1);

关于c# - 尝试在 c# 中使用 dllimport 读取或写入 protected 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16674616/

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