如这篇文章所述:http://blog.csdn.net/duyiwuer2009/article/details/7570921
Java将null传递给C/C++代码是很容易出现问题,那么如何处理呢?看下面这个例子:
在C/C 代码中判断传递过来的对象是否为NULL
class JNIString
{
static
{
System.loadLibrary("JNIString");
}
public static native String strMethod(String s);
}
/*
javac JNIString.java
javah JNIString.java // get the file JNIString.h
*/
#include "JNIString.h"
#include <string.h>
JNIEXPORT jstring JNICALL Java_JNIString_strMethod(JNIEnv *env, jclass jcls, jstring jstr)
{
int i;
char str2[128];
if(jstr == NULL) // 判断传递过来的对象是否为NULL
{
printf("null\n");
return NULL; // 此外,也可以返回NULL,Java得到的将是null
}
const char *str = env->GetStringUTFChars(jstr, NULL); // must be const
// const jchar * GetStringChars(JNIEnv *env, jstring string, jboolean *isCopy);
printf("%s\n", str);
strcpy(str2,str);
env->ReleaseStringUTFChars(jstr, str);
return env->NewStringUTF(str2);
}
/*
set java_inc=E:\FILES\java\jdk1.6.0_29\include
cl -I%java_inc% -I%java_inc%\win32 -LD JNIString.c -FeJNIString.dll
*/
public class Test
{
public static void main(String[] args)
{
String str = "abc123abc"; // 123中国123湖北123武汉123
String s1 = new String(str);
String s2 = JNIString.strMethod(s1);
System.out.println(s2);
str = null;
s2 = JNIString.strMethod(str);
}
}