从C#调用C代码 - 遇到了几个问题

Sha*_*ogs 7 c c#

我有一些C代码,我尝试使用C#.大部分转换都已完成.我有几个问题.

"C"代码的一部分看起来像这样.

typedef struct r_GetCPL {

  UInt8 Storage;
  UInt8 Key[16];             //(1) 

  UInt8 *Buff;               //(2)
  Array16 *CryptoKeyIDs;     //(3)

} REPLY_GETCPL;
Run Code Online (Sandbox Code Playgroud)

在'C'中定义的别名

typedef unsigned char      UInt8;
typedef unsigned short     UInt16;
typedef unsigned long      UInt32;
typedef unsigned long long UInt64;

typedef UInt8   Array8[8];
typedef UInt8   Array16[16];
typedef UInt8   Array32[32];
typedef UInt8   Array64[64];
typedef UInt8   Array128[128];
Run Code Online (Sandbox Code Playgroud)

我假设我可以用直接结构定义替换typedef.这样好吗?我定义的等效C#结构是,

public struct REPLY_GETCPL 
{
  Byte Storage;
  Byte[16] Key;          //(1) Is this right?

  UInt8 *Buff;           //(2)  What is the equivalent?
  Array16 *CryptoKeyIDs; //(3)  What is the equivalent?
}
Run Code Online (Sandbox Code Playgroud)

此外,有几种方法导入我被困在

void hex_print(char* data, UInt32 length);
DRMKLVItem *NewDRMKLVItem(UInt32 lenBuff, UInt32 cmdId);
RESULT DRMKLVLengthDecode(const UInt8 *s, UInt32 *pLen);
Run Code Online (Sandbox Code Playgroud)

C#

//I think this one is defined right
[DllImport("DoremiSource.dll")]
public static extern void hex_print([MarshalAs(UnmanagedType.LPStr)]string data, UInt32 length);

//(How to convert the function return type?)
[DllImport("DoremiSource.dll")]
public static extern DRMKLVItem *NewDRMKLVItem(UInt32 lenBuff, UInt32 cmdId);  //(4)

//(How do i convert the function parameters here)
[DllImport("DoremiSource.dll", CharSet = CharSet.Ansi)]
public static extern int DRMKLVLengthDecode(const UInt8 *s, ref UInt32 pLen);  //(5)
Run Code Online (Sandbox Code Playgroud)

Sut*_*nil -1

如果您尝试“转换”为 C#,最好使用类而不是结构。

例如,您struct REPLY_GETCPL作为一个班级会更好,因为我看到您也在尝试使用指针。此外,您还可以将某些与结构相关联的方法放入类中,并在该类的对象内使用组合功能。

  • 这是一个可怕的建议。`REPLY_GETCPL` 应该是一个结构。 (4认同)