考虑以下结构
/*Structure defined in unmanaged dll written in cpp*/
struct NSCASR_RCG_RES_ST
{
unsigned int ulSizeBytes;
unsigned int ulWarnings;
unsigned short usNumPhrases;
wchar_t* pstrWaveformURI;
unsigned int ulWaveformSizeBytes;
unsigned int ulWaveformDuration;
};
/*Structure defined in c#*/
struct NSCASR_RCG_RES_ST
{
unsigned int ulSizeBytes;
unsigned int ulWarnings;
unsigned short usNumPhrases;
String pstrWaveformURI;
unsigned int ulWaveformSizeBytes;
unsigned int ulWaveformDuration;
};
在我无法想象的DLL(cpp)中,我通过传递结构的地址来调用功能,如下所示:
NSCASR_RCG_RES_ST result_recognize;
ASR_Recognize_ResultsGet(&result_recognize);
在我的托管DLL中,定义就像
void ASR_Recognize_ResultsGet(NSCASR_RCG_RES_ST *recognize)
{
/*MRCP_MD_TO_ASR is namespace and Constants is class name
which consists of structure NSCASR_RCG_RES_ST */
MRCP_MD_TO_ASR::Constants::NSCASR_RCG_RES_ST *pRecognitionResults;
pRecognitionResults = (MRCP_MD_TO_ASR::Constants::NSCASR_RCG_RES_ST *)recognize;
MRCP_MD_TO_ASR::ASR_API::ASR_Recognize_ResultsGet(*pRecognitionResults);
}
在C#代码中,我分配了以下成员
public static int ASR_Recognize_ResultsGet(ref Constants.NSCASR_RCG_RES_ST pRecognitionResults)
{
pRecognitionResults = speech_results;
pRecognitionResults.ulSizeBytes = 200;
return 0;
}
但是当我在执行语句后看到result_recognize的内容时 将值200分配给usNumPhrases变量而不是ulSizeBytes
答案 0 :(得分:0)
我得到的解决方案是,显式添加structlayout,并使用charset,因为c#使用unicode 16,如果我们使用IntPtr概念,则必须将其设置为unicode 8
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct NSCASR_RCG_PHRASE_ST
{
[FieldOffset(0)]
public ushort usConfidence;
[FieldOffset(2)]
public ushort usNumItems;
[FieldOffset(4)]
public short sGrammarIndex;
[FieldOffset(6)]
public short sGrammarType;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public unsafe struct NSCASR_RCG_RES_ST
{
[FieldOffset(0)]
public uint ulSizeBytes;
[FieldOffset(4)]
public uint ulWarnings;
[FieldOffset(8)]
public ushort usNumPhrases;
[FieldOffset(12)]
public IntPtr pstrWaveformURI;
[FieldOffset(16)]
public uint ulWaveformSizeBytes;
[FieldOffset(20)]
public uint ulWaveformDuration;
}