简体   繁体   中英

Sending UTF-8 chars C# to C does not work properly

I work with SQLite for C. I try to send UTF-8 Chars to .dll from c# app but everytime it's work different. For example sometimes it add "değirmenci" and another time with same code it add "değirmencil" but I don't change the word. And sometimes it's adding samething in the UNIQUE column ( I think there is a char but it is not visible like 0x01 in ascii) Sorry about my English.

This is my c# code;

    [DllImport("dllfile.dll", CharSet = CharSet.Unicode)]

static void Main()
{
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes("değirmenci");
    int r;
    //
    IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
    Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);

    IntPtr ch = Tahmin_Baslat();

    r = Sozcuk_Ekle(unmanagedPointer);
    Console.WriteLine(r);
    Console.Read();
    //
}

and this is my C code

    int Sozcuk_Ekle(const char* kok,int tip_1=1,int tip_2=0,int tip_3=0)
{
    sqlite3 *ch; 
    int rc; 
    char *HataMsj = 0; 

    rc = sqlite3_open(veritabani, &ch); // Veritabanının açılması

    if( rc )
    {
        return HATA_DEGERI;
    }

    char buff[strlen(kok) + 64];
    sprintf(buff,"INSERT INTO kokler (kok,tip_1,tip_2,tip_3) VALUES('%s',%d,%d,%d)",kok,tip_1,tip_2,tip_3); // Verilerin Birleştirilmesi
    sqlite3_exec(ch,buff,GeriBildirim,0,&HataMsj); // Komutun Yürütülmesi
    sqlite3_close(ch); // Veritabanını kaynaklarının serbest bırakılması
    return DOGRU_DEGERI; // Doğru Dönder
}

(header files etc. included) And it is how it goes: http://i.stack.imgur.com/BJ4fE.png

Solution
Adding NULL terminator to end of the bytes. byte[] bytes = System.Text.Encoding.UTF8.GetBytes("değirmenci\\0"); like this.

Check calling convention in the DllImport attribute (should be Cdecl ). And add a NULL terminator to your UTF-8 string:

byte[] bytes = System.Text.Encoding.UTF8.GetBytes("değirmenci" + '\0');

This will add NULL terminator to the resulting UTF-8 string (which is not needed for native .NET strings).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM