【问题标题】:Attempting to access byte array in C# from C++ Dll尝试从 C++ Dll 访问 C# 中的字节数组
【发布时间】:2013-11-23 05:51:18
【问题描述】:

所以我试图从 C++ DLL 推送一个无符号字符数组,并希望在 C# GUI 中访问它。我将 C# 设置为 IntPtr,我正在尝试 Marshal.Copy 字节数组,但 IntPtr 始终为 NULL,我哪里错了!

任何帮助将不胜感激。

下面是代码:

C++ DLL 头文件部分

class TEST_API TestClass
{
public:
TestClass(void);
~TestClass(void);

void GetData( unsigned char * testData, unsigned size );

unsigned char testInfo[4096];
};
#ifdef __cplusplus
extern "C" {
#endif
extern TEST_API TestClass* CreateTestClass();
extern TEST_API void DisposeTestClass(TestClass* pObject);
extern TEST_API void TestGetData( TestClass* pObject, unsigned char * testData );
#ifdef __cplusplus
}
#endif

这是 C++ DLL 部分,代码太多,放不下整个内容

extern "C" TEST_API void TestGetData( TestClass* pObject, unsigned char * image )
{
   if(pObject != NULL)
      pObject->GetData( image );
}
void TestClass::GetData( unsigned char * testData )
{
   for ( int i=0; i < 64; i++ )
      for ( int j=0; j < 64; j++ )
             testInfo[j + i*64] = j;
   testData = testInfo;
}

我做的C#代码如下:

IntPtr trial = new IntPtr();
testing.RetrieveTestData(trial, 64, 64);

byte[] managedArray = new byte[64*64];
Marshal.Copy(trial, managedArray, 0, 64*64);

for (int i = 0; i < 64; i++)
   for (int j = 0; j < 64; j++)
      Console.WriteLine(managedArray[j + i * 64]);

基本上每次试验的IntPtr都是0

我希望有人可以帮助我解决这个问题。谢谢

【问题讨论】:

  • 而 RetrieveTestData 究竟做了什么?
  • RetrieveTestData 基本上是在 C++ DLL 中调用 GetData,我希望 TestData 能够获取成员变量 testInfo 的地址,并传递给 C#
  • void GetData(unsigned char * testData, unsigned size);和 void TestClass::GetData( unsigned char * testData ) 两个不同的签名
  • 您的本机代码不正确。 testData = testInfo; 对客户端没有任何影响,您需要将内存复制到 testData。请同时显示 RetrieveTestData 代码和 PInvoke 声明。

标签: c# c++


【解决方案1】:

trial 作为输入参数传递给 RetrieveTestData - 这意味着调用者不能更改它。要由调用者更改,参数必须是 ref 或 out

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多