从c#调用常规dll函数 - 内存分配问题?

时间:2009-11-17 23:58:53

标签: c# memory dll memory-management

嗨chaps(和chappettes)

具有导出功能的常规C dll

int GetGroovyName(int grooovyId,char * pGroovyName,int bufSize,)

基本上你传给它一个ID(int),一个预先分配了内存的char *缓冲区,传入缓冲区的大小。

pGroovyName充满了一些文字。 (即它基于groovyID的查找)

问题是如何从c#中最好地调用它?

欢呼声

巴兹

3 个答案:

答案 0 :(得分:3)

在C#方面,您将拥有:

[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

答案 1 :(得分:1)

您可以在C#中使用DLLImport。

选中此http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx

来自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);
    }
}

答案 2 :(得分: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成功,它打印出groovy id为1的字符串值,否则打印失败。 希望这可以帮助。 汤姆

相关问题