尝试在C#中使用dllimport读取或写入受保护的内存 [英] Attempted to read or write protected memory with dllimport in c#
问题描述
我的项目有问题:
在dll c ++中:
I have a problem with my project: In 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:
and I use to dllimport in c#:
[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();
}
}
当我运行程序时,此程序显示错误:
尝试读取或写入受保护的内存。这通常表明其他内存已损坏
when i run the program, this program show error : Attempted to read or write protected memory. This is often an indication that other memory is corrupt
您知道什么错误以及如何解决?
谢谢!
what error do you know and how to resolved ? thank you!
推荐答案
您不需要 convertStringToByte
方法在这里。您可以告诉运行时将字符串打包为 char *
。另外,我建议您使该方法返回 IntPtr
,如下所示:
You don't need a convertStringToByte
method here. You can tell the runtime to marshal your string as a char *
. Also, I would suggest that you make the method return an IntPtr
, like this:
[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);
然后可以用以下方式调用它:
You can then call it with:
IntPtr tree = buildKDTree(urlImg);
int result1 = results(urlImg, 50, tree);
Console.WriteLine("results = {0}",result1);
这篇关于尝试在C#中使用dllimport读取或写入受保护的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!