[英]calling function from regular dll from c# - memory allocation issue?
嗨,小伙子们
具有带有导出功能的常规C dll
int GetGroovyName(int grooovyId,char * pGroovyName,int bufSize,)
基本上,您传递给它一个ID(int),一个带有内存预分配的char *缓冲区以及传入的缓冲区大小。
pGroovyName充满了一些文本。 (即基于groovyID的查找)
问题是如何最好地从c#调用它?
干杯
蜂鸣器
在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
您可以在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);
}
}
看一下这个片段,从理论上说明它的外观:
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的字符串值,否则打印失败。 希望这可以帮助。 汤姆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.