歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

C# C++ Java接口類型轉換

最近這幾天做了一個兼職 ,主要是把C語言以及C#語言封裝的dll,經過C++中轉為Java語言支持的,主要其中的問題就是類型轉換,在此列出常用類型的轉換過程。

#include "stdafx.h"
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include "www_cnblogs_com\cyjwdm0503.h"
#include <malloc.h>
#include <Windows.h>

using namespace std;
using namespace  System::Runtime::InteropServices;
using namespace  System;

//char* ->c#
System::String^ charptrtoCstring( const char* str )
{
    System::String^ str1  =  Marshal::PtrToStringAnsi((IntPtr)(char*)str);
    return str1;
}


//C#->char*
char* Cstringtocharptr( System::String^ s )
{
    char* buffer = (char*)(void*)Marshal::StringToHGlobalAnsi(s);
    return buffer;
}


//jstring ->char*
char* jstringTocharptr( JNIEnv *env, jstring jstr )
{ //UTF8/16轉換成gb2312
    int length = (env)->GetStringLength(jstr );
    const jchar* jcstr = (env)->GetStringChars(jstr, 0 );
    char* rtn = (char*)malloc( length*2+1 );
    int size = 0;
    size = WideCharToMultiByte( CP_ACP, 0, (LPCWSTR)jcstr, length, rtn,(length*2+1), NULL, NULL );
    if( size <= 0 )
        return NULL;
    (env)->ReleaseStringChars(jstr, jcstr );
    rtn[size] = 0;
    return rtn;
}

//char* ->jstring
jstring charptrTojstring( JNIEnv* env, const char* str )
{//gb2312轉換成utf8/16
    jstring rtn = 0;
    int slen = strlen(str);
    unsigned short * buffer = 0;
    if( slen == 0 )
        rtn = (env)->NewStringUTF(str );
    else
    {
        int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
        buffer = (unsigned short *)malloc( length*2 + 1 );
        if( MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length ) >0 )
            rtn = (env)->NewString(  (jchar*)buffer, length );
    }
    if( buffer )
        free( buffer );
    return rtn;
}

//jchar ->char
char jchartochar( jchar c )
{
    char ch = (char)(c & 0x00ff);
    return ch;
}

//char* ->jchar
jchar charTojchar( char c )
{
    jchar ch = (jchar)(c | 0xff00);
    return ch;
}

//char ->C#
System::Char chartoChar( char c )
{
    System::Char C = (System::Char)((int)(c));
    return C;
}

//C#->char
char Chartochar( System::Char c )
{
    char C = (char)((int)(c));
    return C;
}

Copyright © Linux教程網 All Rights Reserved