2010-03-08 135 views
1

時,我有一個函數的定義在我的VC++的Win32 DLLC++訪問衝突調用DLL函數

DEMO2_API void ProcessData(char* i_buff, unsigned short i_len, char* o_buf, 
unsigned *o_len, unsigned short *errorCode) 
{ 
    __describe (i_buff,&i_len,o_buf,o_len,errorCode); 
} 

此DLL功能是由一個C#應用程序調用。 被調用時,它會生成訪問衝突異常。

reasearching我發現後,我的問題的原因。

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/6e843243-baf4-4eb1-8a20-c691ad47762c

但不明白它們究竟是什麼在示例代碼doinng。 有人可以解釋它嗎?

在外部分配內存後,C#中的P/Invoke簽名是什麼?

+0

您是否允許將C++ DLL編譯爲C++/CLI託管程序集? C++/CLI同時理解.NET數組(cli :: array )和本機內存管理,因此它使得這個任務變得非常簡單。 – 2010-03-08 22:20:44

+0

但我該怎麼做?..任何例子?? – Manjoor 2010-03-09 01:38:04

回答

0

我改變O_len的傳遞模式代替裁判的和它的作品。

讓每個人都給出好的答案和評論。我希望這對其他社區成員(以及那些使用Google搜索的...)有用

0

C#使用IntPtr來表示外部分配的內存。 C#指針和引用只能與垃圾收集器提供的內存一起使用。

System.InteropServices.Marshal類提供了一些用於與由IntPtr表示的本機內存區進行交互的方法,當然它們不是類型安全的。

但我沒有看到你的函數中可能返回指向已分配內存的任何內容。你需要一個雙指針參數或者一個指針返回值,而你沒有。

編輯添加的例子的要求:

// this doesn't work right 
void external_alloc_and_fill(int n, int* result) 
{ 
    result = new int[n]; 
    while (n-- > 0) { result[n] = n; } 
} 

extern external_alloc_and_fill(int n, int* result) 
int a = 5; 
fixed (int* p = &a) { 
    external_alloc_and_fill(17, p); 
    // p still points to a, a is still 5 
} 

更好:

// works fine 
void external_alloc_and_fill2(int n, int** presult) 
{ 
    int* result = *presult = new int[n]; 
    while (n-- > 0) { result[n] = n; } 
} 

extern external_alloc_and_fill2(int n, ref IntPtr result) 
int a 5; 
IntPtr p = &a; 
external_alloc_and_fill2(17, ref p); 
// a is still 5 but p is now pointing to the memory created by 'new' 
// you'll have to use Marshal.Copy to read it though 
+0

@ Ben Voigt 第三個參數* o_buf將會返回到我的應用程序。我需要它作爲字節數組 – Manjoor 2010-03-08 16:27:26

+0

@ Manjoor:調用者分配空間並將指針傳遞給它,或者被調用者分配空間並需要將指針存儲在某處,即指向指針。沒有辦法通過值傳遞指針(比如你的o_buf是)可以用來返回被調用者內部分配的緩衝區。 – 2010-03-08 22:19:03

+0

hmmmm。你能通過一個4行的例子向我展示嗎? – Manjoor 2010-03-09 01:36:39