2009-11-17 47 views
0

喜CHAPS(和chappettes)從C#中的常規DLL調用函數 - 內存分配問題?

與導出功能

INT GetGroovyName(INT grooovyId,字符* pGroovyName,詮釋由bufSize)

基本上你傳遞一個ID一個常規的C DLL( int),一個預先分配了內存的char *緩衝區和傳入的緩衝區的大小。

pGroovyName被填充一些文本。 (即它的基於groovyID的查找)

問題是我該如何最好地從c#中調用?

歡呼

巴茲

回答

1

您可以在C#中使用的DllImport。

檢查從MSDN

using System; 
using System.Runtime.InteropServices; 

class Example 
{ 
    // Use DllImport to import the Win32 MessageBox function. 
    [DllImport("user32.dll", CharSet = CharSet.Unicode)] 
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); 

    static void Main() 
    { 
     // Call the MessageBox function using platform invoke. 
     MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0); 
    } 
} 
+0

-1您發佈的示例不允許通過非託管代碼修改字符串。 – Gonzalo 2009-11-18 00:09:02

3

在C#側這http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx

代碼,你會:

[DllImport("MyLibrary")] 
extern static int GetGroovyName(int grooovyId, StringBuilder pGroovyName, int bufSize); 

而你把它想:

StringBuilder sb = new StringBuilder (256); 
int result = GetGroovyName (id, sb, sb.Capacity); // sb.Capacity == 256 
+0

+1 - 使用StringBuilder比在我的例子中使用char []更好。 – 2009-11-18 00:11:54

0

有一個看看這個片段演示(理論上)應該如何看待:

using System; 
using System.Runtime.InteropServices; 
using System.Text; // For StringBuilder 

class Example 
{ 
    [DllImport("mylib.dll", CharSet = CharSet.Unicode)] 
    public static extern int GetGroovyName(int grooovyId, ref StringBuilder sbGroovyName, int bufSize,) 

    static void Main() 
    { 
     StringBuilder sbGroovyNm = new StringBuilder(256); 
     int nStatus = GetGroovyName(1, ref sbGroovyNm, 256); 
     if (nStatus == 0) Console.WriteLine("Got the name for id of 1. {0}", sbGroovyNm.ToString().Trim()); 
     else Console.WriteLine("Fail!"); 
    } 
} 

我設置了StringBuilder的是256最大容量,你可以定義更小的東西,假設它返回0就是成功,它打印出的字符串值爲1的常規ID,否則打印失敗。 希望這有助於。 Tom

+0

你打我吧貢薩洛.... :) – t0mm13b 2009-11-18 00:11:00

+0

嘿。順便說一句,沒有'ref'那裏需要... – Gonzalo 2009-11-18 00:18:11

+0

嗨有 當我從這個例子中進入dll的sbGroovyNm是一個糟糕的指針和崩潰的應用程序... 所以DLL不認爲有內存分配給sbGroovyNm 嗡嗡聲 – Buzz 2009-11-18 00:41:17