JNI:如何从Java Native Method调用c ++函数

时间:2012-05-14 09:55:12

标签: java c++ java-native-interface

我正在研究一些我正在使用jni的java应用程序。那么现在我想从JNI方法中调用纯c ++函数。我正在这样做,如下面的代码所示。这里创建了DLL,但是当我尝试运行时,我得到错误 java.lang.UnsatisfiedLinkError:找不到依赖库。我正在视觉工作室创建我的DLL。所以告诉我在调用c ++函数时我做错了什么。

这是我的.cpp文件的代码

#include "SensorDetect.h"
#include <stdio.h>
#include <windows.h>
// Include specific Tools header
#include "Tools.h"
   // Include IO_XRayUSB_MD_VC80 header
#include "IO_XRayUSB.h"

// Include IO_XRayUSB_MD_VC80 library
#pragma message ("Using : IO_XRayUSB_MD_VC80.lib")
#pragma comment(lib, "IO_XRayUSB_MD_VC80.lib")

//// Custom user Callback function which is called by IO_XrayUsb when a device is plugged or unplugged
void _stdcall DevicePlugUnplugCallback(XRay_CALLBACK * pCallBackInfo, int nCallBackCount)
{
    if (pCallBackInfo && (nCallBackCount > 0))
    {
        for (int nDeviceIndex = 0; nDeviceIndex < nCallBackCount; nDeviceIndex ++)
        {
            switch(pCallBackInfo[nDeviceIndex].nState)
            {
                case XRAY_USB_PLUGGED_DEVICE :
                    printf("\n=>Callback Device: %s has been Plugged...\n\n", pCallBackInfo[nDeviceIndex].pcDeviceName);
                    break;
                case XRAY_USB_UNPLUGGED_DEVICE :
                    printf("\n=>Callback Device: %s has been Unplugged...\n\n", pCallBackInfo[nDeviceIndex].pcDeviceName);
                    break;
                default:
                    break;
            }
        }
    }
}


extern "C"
JNIEXPORT void JNICALL Java_sensordetect_SensorDetect_getDevice(JNIEnv * env, jclass cl)
{

     const int nNbMaxDevices = 10;
    char pDeviceList[nNbMaxDevices][260];
    int nDeviceCount = 10;
    XRay_HANDLE hDevice;
    XRay_SENSOR_INFO SensorInfo;


    //int nTriggerMode = GetChoice(1, "Choose Trigger Mode:\t0:XVIS_detection    1:TWI_request_detection");
    char pcBuffer[100];
    int nKey;

        nKey=0;

            int nTriggerMode=nKey;

    try
    {
        // XRay_RegisterCallBackPlugDevice to be notified of device plug/unplug
**//This function call creates problem in loading dll. error:Can't find dependent libraries**
     BOOL bSuccess = XRay_RegisterCallBackPlugDevice(DevicePlugUnplugCallback);    


        //for (int nIndex = 0; nIndex < 1; nIndex ++)
            printf("\tFound device : %s\n", pDeviceList[0]);

    }
    catch (...) // catch own CMyException
        {
            //e.ShowReason();
        }

    }

2 个答案:

答案 0 :(得分:1)

IO_XRayUSB_MD_VC80.dll或其中一个dependents不在PATH环境变量中列出的某个目录中,或者不在运行应用程序的同一目录中。

要获取DLL所依赖的DLL列表,可以使用dumpbin.exe

  

dumpbin.exe / DEPENDENTS C:\ path \ to \ IO_XRayUSB_MD_VC80.dll

答案 1 :(得分:1)

确保在启动程序时指定-Djava.library.path=C:\path\to\DLLs选项,和/或在Windows PATH中包含DLL的目录。