【发布时间】:2014-03-19 00:00:02
【问题描述】:
我为一个 c 控制台应用程序创建了一个包装器,我在其中定义了一个结构来将输出传递给 c# windows 窗体。 该结构包含一个必须在 c# 代码中正确解释的 char* 变量。我使用了 IntPtr 类型,但没有得到想要的结果,只有一个我认为是可能的内存地址的数字。
C部分:
struct struct_name{
int a;
char* s;
}
extern __declspec(dllexport) struct_name compute_calc(int opt, char* file_1, char* file_2)
C#部分:
[DllImport("dll_name.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern struct_name compute_calc(int opt, String file1, String file2)
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
public struct struct_name{
Int32 a;
IntPtr s;
}
在应用程序中,我使用以下代码调用函数
struct_name result = levenshtein(1, filePath1, filePath2);
此时我的问题是使用 char*/IntPtr 来提取结构中包含的字符串。我尝试按照How can I convert an unmanaged IntPtr type to a c# string? 中的建议使用编组操作,但我的结果只是一个数字。 有没有其他方法可以将 IntPtr 转换为 c 代码中使用的正确字符串?
edit:结构中的整数被正确传递。问题只在 char*
编辑2:
struct_name result;
{..some code...}--> output int N, char* s0
result.s = (char*)malloc( sizeof(char)*n);
result.a=N;
result.s=_strdup(s0)
return result;
这是建议中要求的 C 部分代码。
【问题讨论】:
-
元帅.PtrToStringAnsi
-
我不确定这是否是原因(自从我进行互操作编码以来已经有一段时间了),但为什么
char*参数您传递为string,而 @987654328 @你声明为IntPtr的结构成员?您是否尝试过将 struct 的成员声明为string? -
还将
CharSet = CharSet.Ansi添加到compute_calcPInvoke 声明。 -
如果我尝试在结构中使用字符串类型,我有一个 System.Runtime.InteropServices.MarshalDirectiveException
-
本地代码使用什么编译器?