【问题标题】:Call VisualBasic DLL in C# works but how to replace a Pchar?在 C# 中调用 VisualBasic DLL 有效,但如何替换 Pchar?
【发布时间】:2016-09-27 08:32:22
【问题描述】:

我有一个用 VisualBasic 编写的旧 DLL,需要用 C# 调用函数。 15 个函数中有 14 个已经在运行(使用控制台项目测试)。剩下的函数有一个参数 PChar 我不知道如何在 C# 中调用它。

一个工作函数如下所示:

[DllImport("C:\\DLL\\visualbasic.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int command(out UInt32 pNumber);

public void Executecommand(out UInt32 pNumber, out int Res)
{
Res = command(out pNumber);
}

不工作的函数有两个参数: 1.输出pData:PChar 2. const pDataLen(这是返回的数据长度)

VB DLL 的手册说,在调用函数之前保留内存并在函数完成后释放内存很重要。 20 个字符应该足够了。

谁能给我一个提示如何调用该函数?当我简单地使用“字符串”时,我得到一个异常: 发生类型 System.AccesViolationException 的未处理异常。 附加信息:试图读取或写入受保护的内存。这通常表明其他内存已损坏。

感谢您的帮助。

【问题讨论】:

  • 这是一个非常无用的sn-p。 PChar 是 Delphi 类型,“out”和“const”没有意义。最有可能正确的参数类型是 StringBuilder,没有 ref 或 out,带有 CharSet.Ansi。调用前将其容量设置为 20。第二个参数肯定是 int 但很难猜测它是否需要参考。
  • 我尝试过使用 stringbuilder。如果我不使用“out”,那么函数会执行,但我在 stringbuilder 变量中没有数据。如果我在 tthe stringbuilder-variable 中使用 out 参数,那么我会遇到与第一次发布时相同的错误。 public void NotWorking(out string pData, int pDataLen, out int Res) { StringBuilder MyStringBuilder = new StringBuilder("", 20); Res = Execute_NotWorking(MyStringBuilder, pDataLen) pData= MyStringBuilder.ToString(); }

标签: c# string pointers pchar


【解决方案1】:

你试过指针吗??

public static extern void NotWorkFunction(out IntPtr pOut, int someConst)

void Main(string[] args)
{
  IntPtr pOut;
  int dataLength;
  string foo;

  NotWorkFunction(pOut, dataLength);
  foo = Marshal.PtrToStringAuto(pOut);
  BlockFree(pOut);
}

【讨论】:

  • 您好 Ar Aui,感谢您的回答。我改变了我的代码,但我得到了和以前一样的错误信息。
【解决方案2】:

解决方案是使用“ref string”而不是“out string”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多