JNI:Java调用C/C++-传递空值(null)的处理方法

6 篇文章 0 订阅

如这篇文章所述: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);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值