DllImport-und char-Marshalling

Ich bin Neuling in C# und Marshalling. Ich muss an meinem C func in C#, aber ich habe einen falschen Rückgabewert von C func (oder ich weiß nicht, wie es zu konvertieren, um die richtige Antwort).

C Quelle:

#include "main.h"

char *Ololo(char *arg, int &n3)
{
    char *szRet;
    szRet=(char*)malloc(strlen(arg)+1);
    strcpy(szRet,arg);
    n3 = strlen(szRet);
    return szRet;
}

C-header:

extern "C" __declspec(dllexport) char *Ololo(char *arg, int &n3);

C# - Quelle:

class Program
{
    [DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
    public static extern IntPtr Ololo([In] char[] arg, ref Int32 n3);

    static void Main(string[] args)
    {
        string n1 = "ololo";
        char[] chars = new char[n1.Length];
        chars = n1.ToCharArray();
        Int32 n3 = 0;
        IntPtr result;
        result = Ololo(chars, ref n3);
        string n4 = Marshal.PtrToStringUni(result,n3);
        Console.WriteLine(n4);
    }
}

Habe ich etwas von dem zurückgeben, wie "o?? ?"

Sorry für schlechtes Englisch

----------------------Gelöst-----------------------

class Program
    {
        [DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
        public static extern IntPtr Ololo([MarshalAs(UnmanagedType.LPStr)]string arg, ref Int32 n3);

        static void Main(string[] args)
        {
            string n1 = "ololo";
            Int32 n3 = 0;
            int n2 = n1.Length;
            IntPtr result;
            result = Ololo(n1, ref n3);
            string n4 = Marshal.PtrToStringAnsi(result, n3);
            Console.WriteLine(n4);
        }
    }

Das funktioniert auch. In n3 habe ich 5 und n4 ololo! Danke für s schnelle Antworten!

btw 'int &n3' ist nicht C, der C++ - notation.
Sie haben nichts gelöst, der code verliert den Speicher für den string.
mögliche Duplikate von Char * marshalling in C#
Passant einen Unterschied gibt Es allerdings: Auf dem link func zurück char * war rewrited void func. In meiner Frage, der erste war wie zu fangen return(char ). Und wenn es einen memory-leak, wie die Kostenlose Rücksendung(char) in c#?

InformationsquelleAutor Treno1 | 2012-09-10

Schreibe einen Kommentar