日期:2014-05-16  浏览次数:20807 次

c#调用c编写的dll 关于指针问题
dll.h文件
#include <string.h>

struct str_dll
{
int    age;
char   par_char3[ 256 ];  
};

struct  dll_test
{  
    char     par_char1[ 256 ];  
    char     par_char2[ 256 ];  
    int*     ptr_int;
float    par_float;
void*    Ptr_void;
str_dll  struct_str_dll;
};

extern "C" __declspec(dllexport)
 int __cdecl change_str_dll(str_dll test_str_dll);

extern "C" __declspec(dllexport)
 int __cdecl foo(int ret);

extern "C" __declspec(dllexport)
int change_dll_test(dll_test*  ptr_dll_test);

dll.cpp文件
#include "test_cpp.h"

int change_str_dll(str_dll test_str_dll)
{
test_str_dll.age = 10;
return 0;
}

int foo(int ret)
{
    return (ret+1);
}
    

//int change_dll_test(char*  buffer1, char* buffer2, double* ptr_double, float par_float, void*    Ptr_void)
int change_dll_test(dll_test*  ptr_dll_test)
{
    strncpy(ptr_dll_test->par_char1, "test buffer1...", 256);
    strncpy(ptr_dll_test->par_char2, "test buffer2...", 256);
int* i;
int j = 99;
i = &j;
ptr_dll_test->ptr_int = i;
ptr_dll_test->par_float = 12;
ptr_dll_test->Ptr_void = i;
ptr_dll_test->struct_str_dll.age = 24;
strncpy(ptr_dll_test->struct_str_dll.par_char3, "test struct is over!", 256);

return 0;
}

c#调用文件如下显示:

[DllImport("TEST_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int change_dll_test(ref dll_test ptr_dll_test);
dll_test ptr_dll_test = new dll_test();
int i = change_dll_test(ref ptr_dll_test);
得到的int*     ptr_int;void*    Ptr_void,是个地址,在c#中如何得到对应的值,具体代码该怎么写 或者说一下方向我自己查
------解决方案--------------------
yourtype t = (yourtype)Marshal.PtrToStructure(ptr,typeof(yourtype))
------解决方案--------------------
引用:
Quote: 引用:

yourtype t = (yourtype)Marshal.PtrToStructure(ptr,typeof(yourtype))
谢谢 还有个问题
C语言函数为int vip_fluoro_set_prms(int structType, void* structPtr)
对应的c#函数 void*函数该怎么改?

你是说在C#里怎么引用吗?
int vip_fluoro_set_prms(int structType, int structPtr)

其中structPtr为获取Struct的IntPtr后传IntPtr.ToInt32()进去
------解决方案--------------------
还没解决吗,友情帮顶吧,这个问题昨天到现在了,还是没解决啊,大神,快来~

------解决方案--------------------
引用:
我将这段代码写成函数时,能确保ptr_dll_test->ptr_int这个值时正确的。这又是为什么?

野指针有不确定性,比如下面的例