调用C DLL函数用char *参数使用的P / Invoke [英] Calling a C DLL Function With char* Parameters With P/Invoke

查看:300
本文介绍了调用C DLL函数用char *参数使用的P / Invoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过这个其他类似的问题,但他们不解决这个特定的问题。我有一个旧的C库具有与toUpperCase功能(作为一个例子)。这需要一个char *,并返回一个char *。然而,返回的指针指向相同的字符串(不要问我,我没有写)

I've read other similar questions on this but they don't solve this particular problem. I have an old C-library with a touppercase function (as an example). This takes a char* and returns a char*. However, the pointer returned is a pointer to the same string (don't ask me I didn't write it).

函数看起来是这样的:

__declspec(dllexport)
char * __cdecl touppercase(char *ps_source)
{
    char *ps_buffer = NULL;

    assert (ps_source != NULL);

    ps_buffer = ps_source;
    while (*ps_buffer != '\0')
    {
        *ps_buffer = toupper(*ps_buffer);
        ps_buffer++;
    }
*ps_buffer = '\0';
    return (ps_source);
}



C#代码来声明这个样子:

The C# code to declare this looks like:

    [DllImport("mydll.dll", EntryPoint = "touppercase",
               CharSet = CharSet.Ansi, ExactSpelling = true,
               CallingConvention = CallingConvention.Cdecl)]
    private static extern System.IntPtr touppercase(string postData);

在我的应用程序这个调用看起来像

The call to this in my app looks like

     string sTest2 = Marshal.PtrToStringAnsi(to_uppercase(sTest));



不过sTest2刚刚结束是一个随机字符串。

However sTest2 just ends up being a random string.

我添加了一个测试功能,使用相同的参数相同的dll但本地分配内存,复制字符串。这工作得很好。 ?为什么原来的版本现在的工作。

I added a test function to the same dll with the same parameters but this allocates memory locally and copies the string. This works fine. Why does the original version now work?

请注意:更新DLL库本身是不是一种选择

Note: Updating the dll libraries themselves isn't an option.

推荐答案

该功能修改的参考,所以你应该使用StringBuilder:

The function is modifying the reference so you should use a stringbuilder:

[DllImport("dll.dll", EntryPoint="touppercase",
CharSet = CharSet.Ansi, ExactSpelling = true,
CallingConvention = CallingConvention.Cdecl)]
private static extern System.IntPtr touppercase(StringBuilder postData);



说它是这样的:

Call it something like this:

    StringBuilder sTest = new StringBuilder("abs");
    touppercase(sTest);
    string result = sTest.ToString();



对于返回指针的解释 - >本福格特

For the explanation of the return pointer -> Ben Voigt

这篇关于调用C DLL函数用char *参数使用的P / Invoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆