JNI方法调用C++类库 <二>

原先布局中的lib文件和jni文件,都是cpp文件,都应该编进库里。因此应该把这两部分合二为一。在c++文件里起线程。

在cpp文件里的终止线程代码可能有误。但是启动线程和启动设备的代码已经验证是正确的。

库文件:dms_jni.cpp

java文件:dms.java

下面是库文件dms_jni.cpp:

#include <jni.h>
#include "Neptune.h"
#include "Platinum.h"

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>


PLT_UPnP upnp;
PLT_DeviceHostReference device;
pthread_t thread;
//NPT_SET_LOCAL_LOGGER("platinum.media.server.file.test")

void* start_dms(void*)
{	
	// setup Neptune logging
	NPT_LogManager::GetDefault().Configure("plist:.level=INFO;.handlers=ConsoleHandler;.ConsoleHandler.colors=off;.ConsoleHandler.filter=42");

	printf("baojinyu--------dms_lib---->start_dms.\n");
	device = new PLT_FileMediaServer("/data/local", 
								"UPnP Media Server(friendlyname)");
	NPT_List<NPT_IpAddress> list;
	PLT_UPnPMessageHelper::GetIPAddresses(list);
	NPT_String ip = list.GetFirstItem()->ToString();

	device->m_ModelDescription = "Platinum Media Server";
	device->m_ModelURL = "http://www.plutinosoft.com/";
	device->m_ModelNumber = "1.0";
	device->m_ModelName = "Platinum Media Server";
	device->m_Manufacturer = "Plutinosoft";
	device->m_ManufacturerURL = "http://www.plutinosoft.com/";

	upnp.AddDevice(device);
	printf("baojinyu--------dms_lib---->start_dms.\n");
	upnp.Start();			
}

int stop_dms()
{
	printf("baojinyu--------dms_lib---->stop_dms.\n");
	upnp.Stop();
	return 0;
}

JNIEXPORT jint JNICALL Java_dms_dmsThreadBegin(JNIEnv *env, jclass clazz)
{
	
	int retval;
	retval = pthread_create(&thread, NULL, start_dms, NULL); 
	if(retval != 0)
	{
		printf("create thread fail!\n");
		return -1;
	}  
	printf("pthread_create success.\n");
	return 0;
}

JNIEXPORT jint JNICALL Java_dms_dmsThreadEnd(JNIEnv *env, jclass clazz)	
{
	stop_dms();
	pthread_exit(NULL);
	return 0;
}

dms.java:

/** 
 * file: dms.java
 * {@hide}
 */
public class dms
{
    // can't instantiate this class
    private dms()
    {
    }

    public static native int dmsThreadBegin();
    public static native int dmsThreadEnd();
}

通过命令javac dms.java && javah dms生成c/c++头文件dms.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class dms */

#ifndef _Included_dms
#define _Included_dms
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     dms
 * Method:    dmsThreadBegin
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_dms_dmsThreadBegin
  (JNIEnv *, jclass);

/*
 * Class:     dms
 * Method:    dmsThreadEnd
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_dms_dmsThreadEnd
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

在应用程序里加载库,声明native方法,即可调用库文件中的方法。





你可能感兴趣的:(java,thread,C++,jni,null,Class)