DLL中:
void Test(void* param)
{
int* temp = (int*)param;
*temp = 253;
}
C#中调用DLL中Test函数:
class Program
{
[DllImport("CIntToVoidPointerDLL2.dll")]
public static extern void Test(IntPtr param);
static void Main(string[] args)
{
IntPtr a = new IntPtr(34);
Test(a);
Console.WriteLine((int)a);
}
}
运行提示:未处理的异常:System.AccessViolationException:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。这样写有什么错误?
还有,简单类型如何传递给DLL中参数为void*的函数?现在可以传递struct,简单类型却搞不定。谢谢
void Test(void* param)
{
int* temp = (int*)param;
*temp = 253;
}
C#中调用DLL中Test函数:
class Program
{
[DllImport("CIntToVoidPointerDLL2.dll")]
public static extern void Test(IntPtr param);
static void Main(string[] args)
{
IntPtr a = new IntPtr(34);
Test(a);
Console.WriteLine((int)a);
}
}
运行提示:未处理的异常:System.AccessViolationException:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。这样写有什么错误?
还有,简单类型如何传递给DLL中参数为void*的函数?现在可以传递struct,简单类型却搞不定。谢谢
{
[DllImport("CIntToVoidPointerDLL2.dll")]
public static extern void Test(ref int param);
static void Main(string[] args)
{
int a = 34;
Test(ref a);
Console.WriteLine((int)a);
}
}既然DLL中是作为int类型的指针,上面的就可以了
如果一定要声明为[DllImport("CIntToVoidPointerDLL2.dll")]
public static extern void Test(IntPtr param);//申请一个int类型大小的空间
IntPtr a = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(a,34);
Test(a);
int b=Marshal.ReadInt32(a);
Marshal.FreeHGlobal(a);
Console.WriteLine(b);http://msdn.microsoft.com/zh-cn/library/atxe881w(v=VS.80).aspx
public static extern void Test(ref int param);
int a = 34;
Test(ref a);IntPtr i= Marshal.AllocHGlobal(len);
分配空间
2.
IntPtr a = new IntPtr(34);
Test(a);
Console.WriteLine((int)a);//a是int的指针,并且这个指针初始化指向了错误的内存。
应该这么写:
int myInt;
int* pInt = &myInt;
IntPtr ptr = new IntPtr(pInt);
Test(ptr);
[DllImport("CIntToVoidPointerDLL2.dll",CallingConvention=CallingConvention.Cdecl)]
public static extern void Test(IntPtr param);
static unsafe void Main(string[] args) {
int myInt;
int* pInt = &myInt;
IntPtr ptr = new IntPtr(pInt);
Test(ptr); }