【问题标题】:Using windows' CreateEvent() function from java using JNA使用 JNA 从 java 中使用 windows 的 CreateEvent() 函数
【发布时间】:2016-01-12 00:27:19
【问题描述】:

我编写了以下类来包装 win32 事件对象的创建

import com.sun.jna.*;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.Kernel32;

/**
 * Wraps a (newly-created) native win32 event object and allows you to signal it.
 * 
 * The created event object is manual-reset and is initially un-set.
 */
public final class Win32Event
{
    private static final Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("Kernel32", Kernel32.class);

    private WinNT.HANDLE m_handle = null;

    public Win32Event(String in_eventName)
    {
        assert null != in_eventName;

        m_handle = INSTANCE.CreateEvent(null, true, false, in_eventName);

        assert !Pointer.NULL.equals(m_handle.getPointer());
    }

    public void signal()
    {
        assert isValid();

        INSTANCE.SetEvent(m_handle);
    }

    /**
     * @return True if the event handle hasn't been freed with free().
     */
    public boolean isValid()
    {
        return null != m_handle;
    }

    /**
     * Frees the wrapped event handle. This must be done to prevent handle leaks.
     */
    public void free()
    {
        if (isValid())
        {
            INSTANCE.CloseHandle(m_handle);

            m_handle = null;
        }
    }

    @Override
    protected void finalize()
    {
        free();
    }
}

我在 Windows 7 机器上使用 jna 3.3,当我尝试创建此类的实例时,我得到以下堆栈跟踪。

线程“主”java.lang.UnsatisfiedLinkError 中的异常:错误 查找函数“CreateEvent”:指定的过程无法 找到了。

在 com.sun.jna.Function.(Function.java:179) 在 com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:347) 在 com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:327) 在 com.sun.jna.Library$Handler.invoke(Library.java:203) 在 $Proxy0.CreateEvent(未知来源)在 Win32Event.(Win32Event.java:23)

我真的是 JNA 的新手,不知道我做错了什么。

【问题讨论】:

    标签: java winapi jna


    【解决方案1】:

    我通过将代码从使用我在顶部定义的静态变量执行 INSTANCE.[method] 更改为使用 kernel32.INSTANCE.[method] 来修复它。

    我通过查看 kernel32 的定义并注意到它具有静态 INSTANCE 变量发现了这一点。

    【讨论】:

    • in_eventName 断言是可疑的。事件可以命名或未命名,但要创建未命名事件,您必须将空字符指针传递给实际的CreateEvent() DLL 函数。 Kernel32.INSTANCE.CreateEvent() 是否说明了这一点?此外,在实际 DLL 中,CreateEvent() 导出为 CreateEventA() 用于 Ansi 和 CreateEventW() 用于 Unicode 名称。 Kernel32.INSTANCE.CreateEvent() 是否也说明了这一点?
    • 对于我的用例,我总是希望事件被命名。对于您的其他评论,我只能希望他们使用 W 版本,因为 Java 的字符串是 Unicode
    • JNA 自动处理映射到“ansi”或 unicode 以及相关的字符串转换;见W32APIOptions.DEFAULT_OPTIONS,用于初始化kernel32库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多