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;
}