使用 JNA 的 C 回调使 JRE 崩溃

2023-11-26

我在 JNA 中处理回调时遇到问题。

我正在尝试使用 C API,它使用回调来处理多个会话事件(登录、注销、连接问题...)。
会话对象(称为sp_session) 是一个不透明的结构。所有回调都注册在sp_session_callbacks结构。根据 API,我应该声明回调对象,并将其放入我将在创建时提供的 Config 对象中sp_session目的。如果我不想使用某些回调,我应该用以下命令初始化它们null。该 API 正在使用__stdcall调用约定。

以下是与我的问题相关的 C 标头片段:

#define SP_CALLCONV __stdcall

typedef struct sp_session sp_session; ///< Representation of a session

typedef enum sp_error {
    SP_ERROR_OK                        = 0,  
    SP_ERROR_BAD_API_VERSION           = 1,
        /* More errors */
} sp_error;

typedef struct sp_session_callbacks {
    /**
     * Called when login has been processed and was successful
     */
    void (SP_CALLCONV *logged_in)(sp_session *session, sp_error error);

    /**
     * Called when logout has been processed. Either called explicitly
     * if you initialize a logout operation, or implicitly if there
     * is a permanent connection error
     *
     * @param[in]  session    Session
     */
    void (SP_CALLCONV *logged_out)(sp_session *session);

    /**
     * Called when there is a connection error, and the library has problems
     * reconnecting to the Spotify service. Could be called multiple times (as
     * long as the problem is present) 
     */
    void (SP_CALLCONV *connection_error)(sp_session *session, sp_error error);

    /* More callbacks */
} sp_session_callbacks;

/**
 * Initialize a session. The session returned will be initialized, but you will need
 * to log in before you can perform any other operation
 */
SP_LIBEXPORT(sp_error) sp_session_create(const sp_session_config *config, sp_session **sess);

这是我的等效 JNA 代码:

sp_session 对象

public class sp_session extends PointerType{

    public sp_session(Pointer address) {
        super(address);
    }
    public sp_session() {
        super();
    }
}

sp_session_callbacks 对象,包含所有回调

public class sp_session_callbacks extends Structure{
    public LoggedIn logged_in;
    public LoggedOut logged_out;
    public ConnectionError connection_error;
}

回调对象(这里是 LoggedIn,但当然每个回调我都有一个)

public interface LoggedIn extends StdCallCallback {
    public void logged_in(sp_session session, int error);
}

本机库,包含所有方法的声明

public interface JLibspotify extends StdCallLibrary{
    int sessionCreate(sp_session_config config, PointerByReference sess);
    int sessionLogin(sp_session session, String username, String password);
    // All the other methods defined by the API
}

和我的主要课程,将它们绑定在一起

public class Test{
    static{
        System.loadLibrary("libspotify");
    }

    public static void main(String[] args){
        JLibspotify lib = (JLibspotify)Native.loadLibrary("libspotify", JLibspotify.class);
        sp_session_config cfg = new sp_session_config();
        }
        sp_session_callbacks sessCallbacks = new sp_session_callbacks();
        LoggedIn loggedInCallback = new LoggedIn(){
        public void logged_in(sp_session session, int error) {
             System.out.println("logged_in() called");
            }

        };
        sessCallbacks.logged_in = loggedInCallback;

        cfg.session_callbacks = sessCallbacks;

        PointerByReference sessionPbr = new PointerByReference();

        int error_id = sessionCreate(cfg, sessionPbr); // CRASHES HERE

        sp_session mySession = new sp_session(sessionPbr.getValue());
    }
}

因此,sessionCreate 函数调用使 JRE 崩溃,并在帖子末尾显示跟踪信息EXCEPTION_ACCESS_VIOLATION (0xc0000005) problematic frame: C [jna3666290841889849729.dll+0xa3f4].

看起来logging_in回调导致了这个,因为当我将其设置为null运行正常。另外,如果我初始化connection_error回调,具有完全相同的签名,它也不会崩溃。

我正在运行 JNA 3.2.7 版本。我尝试使用之前的版本(3.0.9),但也失败了。 我正在运行 JDK 1.7 beta 版本,但我尝试使用 1.6,但也失败了。

谢谢你!

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0499a3f4, pid=1368, tid=1344
#
# JRE version: 7.0-b129
# Java VM: Java HotSpot(TM) Client VM (21.0-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# C  [jna3666290841889849729.dll+0xa3f4]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x01b79400):  JavaThread "main" [_thread_in_native, id=1344, stack(0x00340000,0x00390000)]

siginfo: ExceptionCode=0xc0000005, reading address 0x1993053a

Registers:
EAX=0x19930522, EBX=0x100dc77c, ECX=0x00010004, EDX=0x1008d3e0
ESP=0x0038f58c, EBP=0x0038f5b4, ESI=0x0038f5a4, EDI=0x100b79b0
EIP=0x0499a3f4, EFLAGS=0x00210212

Top of Stack: (sp=0x0038f58c)
0x0038f58c:   100dc77c 0038f5a4 00010004 0038f688
0x0038f59c:   05983de0 05981330 0598289c 05983de0
0x0038f5ac:   05983de0 00000014 0038f688 1008d3ea
0x0038f5bc:   05983de0 10030d77 0038fc44 100b79b0
0x0038f5cc:   ffffffff 1008d334 00000000 05983de0
0x0038f5dc:   1008d3e0 05983fc4 1008d9fd 0038f770
0x0038f5ec:   00000000 00000000 7275016a 055310b0
0x0038f5fc:   00000000 00010001 00000000 00000000 

Instructions: (pc=0x0499a3f4)
0x0499a3d4:   01 00 89 e5 57 56 8d 75 f0 53 83 ec 1c 8b 7d 14
0x0499a3e4:   8b 5f 4c 8b 03 89 4c 24 08 89 74 24 04 89 1c 24
0x0499a3f4:   ff 50 18 83 ec 0c 85 c0 0f 94 c0 0f b6 c0 85 c0
0x0499a404:   89 45 ec 75 19 8b 03 31 d2 89 54 24 08 89 74 24 


Register to memory mapping:

EAX=0x19930522 is an unknown value
EBX=0x100dc77c is an unknown value
ECX=0x00010004 is an unknown value
EDX=0x1008d3e0 is an unknown value
ESP=0x0038f58c is pointing into the stack for thread: 0x01b79400
EBP=0x0038f5b4 is pointing into the stack for thread: 0x01b79400
ESI=0x0038f5a4 is pointing into the stack for thread: 0x01b79400
EDI=0x100b79b0 is an unknown value


Stack: [0x00340000,0x00390000],  sp=0x0038f58c,  free space=317k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [jna3666290841889849729.dll+0xa3f4]  Java_com_sun_jna_Native_initialize_1ffi_1type+0x1054
C  [libspotify.dll+0x8d3ea]  sp_error_message+0x35a
C  [jna3666290841889849729.dll+0xcb77]  Java_com_sun_jna_Native_initialize_1ffi_1type+0x37d7
C  [jna3666290841889849729.dll+0xc7c2]  Java_com_sun_jna_Native_initialize_1ffi_1type+0x3422
C  [jna3666290841889849729.dll+0x4561]  Java_com_sun_jna_Pointer__1getString+0xa31
C  [jna3666290841889849729.dll+0x4d2e]  Java_com_sun_jna_Function_invokeInt+0x2e
j  com.sun.jna.Function.invokeInt(I[Ljava/lang/Object;)I+0
j  com.sun.jna.Function.invoke([Ljava/lang/Object;Ljava/lang/Class;Z)Ljava/lang/Object;+315
j  com.sun.jna.Function.invoke(Ljava/lang/Class;[Ljava/lang/Object;Ljava/util/Map;)Ljava/lang/Object;+214
j  com.sun.jna.Library$Handler.invoke(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;+341
j  $Proxy0.sp_session_create(Lcom/nbarraille/jspotify/model/sp_session_config;Lcom/sun/jna/ptr/PointerByReference;)I+20
j  com.nbarraille.jspotify.main.Test.main([Ljava/lang/String;)V+273
v  ~StubRoutines::call_stub
V  [jvm.dll+0x115f6d]
V  [jvm.dll+0x1b788e]
V  [jvm.dll+0x115fed]
V  [jvm.dll+0xa2507]
V  [jvm.dll+0xac867]
C  [javaw.exe+0x209e]
C  [javaw.exe+0xa23b]
C  [javaw.exe+0xa2c5]
C  [kernel32.dll+0x51194]  BaseThreadInitThunk+0x12
C  [ntdll.dll+0x5b429]  RtlInitializeExceptionChain+0x63
C  [ntdll.dll+0x5b3fc]  RtlInitializeExceptionChain+0x36

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  com.sun.jna.Function.invokeInt(I[Ljava/lang/Object;)I+0
j  com.sun.jna.Function.invoke([Ljava/lang/Object;Ljava/lang/Class;Z)Ljava/lang/Object;+315
j  com.sun.jna.Function.invoke(Ljava/lang/Class;[Ljava/lang/Object;Ljava/util/Map;)Ljava/lang/Object;+214
j  com.sun.jna.Library$Handler.invoke(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;+341
j  $Proxy0.sp_session_create(Lcom/nbarraille/jspotify/model/sp_session_config;Lcom/sun/jna/ptr/PointerByReference;)I+20
j  com.nbarraille.jspotify.main.Test.main([Ljava/lang/String;)V+273
v  ~StubRoutines::call_stub

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
  0x0182fc00 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=4664, stack(0x04170000,0x041c0000)]
  0x0182ac00 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=1728, stack(0x01b20000,0x01b70000)]
  0x01829800 JavaThread "Attach Listener" daemon [_thread_blocked, id=112, stack(0x04020000,0x04070000)]
  0x01826400 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=5836, stack(0x03ea0000,0x03ef0000)]
  0x01819800 JavaThread "Finalizer" daemon [_thread_blocked, id=4724, stack(0x03f80000,0x03fd0000)]
  0x01817800 JavaThread "Reference Handler" daemon [_thread_blocked, id=3940, stack(0x01ad0000,0x01b20000)]
=>0x01b79400 JavaThread "main" [_thread_in_native, id=1344, stack(0x00340000,0x00390000)]

Other Threads:
  0x01816400 VMThread [stack: 0x01a30000,0x01a80000] [id=3876]
  0x01843000 WatcherThread [stack: 0x040d0000,0x04120000] [id=4636]

VM state:not at safepoint (normal execution)

VM Mutex/Monitor currently owned by a thread: None

Heap
 def new generation   total 4928K, used 3630K [0x23450000, 0x239a0000, 0x289a0000)
  eden space 4416K,  82% used [0x23450000, 0x237db858, 0x238a0000)
  from space 512K,   0% used [0x238a0000, 0x238a0000, 0x23920000)
  to   space 512K,   0% used [0x23920000, 0x23920000, 0x239a0000)
 tenured generation   total 10944K, used 0K [0x289a0000, 0x29450000, 0x33450000)
   the space 10944K,   0% used [0x289a0000, 0x289a0000, 0x289a0200, 0x29450000)
 compacting perm gen  total 12288K, used 860K [0x33450000, 0x34050000, 0x37450000)
   the space 12288K,   7% used [0x33450000, 0x33527190, 0x33527200, 0x34050000)
    ro space 10240K,  43% used [0x37450000, 0x3789ce40, 0x3789d000, 0x37e50000)
    rw space 12288K,  53% used [0x37e50000, 0x384c2710, 0x384c2800, 0x38a50000)

Code Cache  [0x01e90000, 0x01f20000, 0x03e90000)
 total_blobs=234 nmethods=82 adapters=88 free_code_cache=32972224 largest_free_block=0

Dynamic libraries:
0x00880000 - 0x008b0000     C:\Program Files\Java\jdk1.7.0\bin\javaw.exe
0x778f0000 - 0x77a2d000     C:\Windows\SYSTEM32\ntdll.dll
0x77070000 - 0x77144000     C:\Windows\system32\kernel32.dll
0x75cf0000 - 0x75d3a000     C:\Windows\system32\KERNELBASE.dll
0x60000000 - 0x60041000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\midas32.dll
0x61000000 - 0x61028000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_base.m32
0x67000000 - 0x67048000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_nt.m32
0x64000000 - 0x64021000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_registry.m32
0x62000000 - 0x6202d000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_extra.m32
0x65000000 - 0x6501a000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_net.m32
0x63000000 - 0x630a6000     C:\Program Files\BitDefender\BitDefender 2011\Active Virus Control\Midas_00078_002\plugin_fragments.m32
0x75e10000 - 0x75eb0000     C:\Windows\system32\ADVAPI32.dll
0x775c0000 - 0x7766c000     C:\Windows\system32\msvcrt.dll
0x75d50000 - 0x75d69000     C:\Windows\SYSTEM32\sechost.dll
0x77670000 - 0x77711000     C:\Windows\system32\RPCRT4.dll
0x76f00000 - 0x76fc9000     C:\Windows\system32\USER32.dll
0x77a50000 - 0x77a9e000     C:\Windows\system32\GDI32.dll
0x77a30000 - 0x77a3a000     C:\Windows\system32\LPK.dll
0x75d70000 - 0x75e0d000     C:\Windows\system32\USP10.dll
0x74830000 - 0x749ce000     C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7600.16661_none_420fe3fa2b8113bd\COMCTL32.dll
0x772f0000 - 0x77347000     C:\Windows\system32\SHLWAPI.dll
0x775a0000 - 0x775bf000     C:\Windows\system32\IMM32.DLL
0x75eb0000 - 0x75f7c000     C:\Windows\system32\MSCTF.dll
0x72740000 - 0x727fe000     C:\Program Files\Java\jdk1.7.0\jre\bin\msvcr100.dll
0x01b80000 - 0x01e89000     C:\Program Files\Java\jdk1.7.0\jre\bin\client\jvm.dll
0x746c0000 - 0x746f2000     C:\Windows\system32\WINMM.dll
0x73920000 - 0x7392c000     C:\Program Files\Java\jdk1.7.0\jre\bin\verify.dll
0x73330000 - 0x73350000     C:\Program Files\Java\jdk1.7.0\jre\bin\java.dll
0x75d40000 - 0x75d45000     C:\Windows\system32\PSAPI.DLL
0x733a0000 - 0x733b3000     C:\Program Files\Java\jdk1.7.0\jre\bin\zip.dll
0x10000000 - 0x10259000     C:\Windows\System32\libspotify.dll
0x77150000 - 0x77185000     C:\Windows\system32\WS2_32.dll
0x77a40000 - 0x77a46000     C:\Windows\system32\NSI.dll
0x75ba0000 - 0x75cbc000     C:\Windows\system32\CRYPT32.dll
0x75ab0000 - 0x75abc000     C:\Windows\system32\MSASN1.dll
0x74ee0000 - 0x74f38000     C:\Windows\system32\WINHTTP.dll
0x74e90000 - 0x74edf000     C:\Windows\system32\webio.dll
0x754c0000 - 0x754d6000     C:\Windows\system32\CRYPTSP.dll
0x75260000 - 0x7529b000     C:\Windows\system32\rsaenh.dll
0x750a0000 - 0x750b7000     C:\Windows\system32\USERENV.dll
0x75a40000 - 0x75a4b000     C:\Windows\system32\profapi.dll
0x75a30000 - 0x75a3c000     C:\Windows\system32\CRYPTBASE.dll
0x728a0000 - 0x728b6000     C:\Program Files\Java\jdk1.7.0\jre\bin\net.dll
0x75480000 - 0x754bc000     C:\Windows\system32\mswsock.dll
0x75470000 - 0x75476000     C:\Windows\System32\wship6.dll
0x73950000 - 0x73960000     C:\Windows\system32\NLAapi.dll
0x75340000 - 0x75384000     C:\Windows\system32\DNSAPI.dll
0x71030000 - 0x71038000     C:\Windows\System32\winrnr.dll
0x71020000 - 0x71030000     C:\Windows\system32\napinsp.dll
0x71000000 - 0x71012000     C:\Windows\system32\pnrpnsp.dll
0x74fd0000 - 0x74fd5000     C:\Windows\System32\wshtcpip.dll
0x74d30000 - 0x74d4c000     C:\Windows\system32\IPHLPAPI.DLL
0x74d20000 - 0x74d27000     C:\Windows\system32\WINNSI.DLL
0x70c60000 - 0x70c66000     C:\Windows\system32\rasadhlp.dll
0x71ba0000 - 0x71bd8000     C:\Windows\System32\fwpuclnt.dll
0x73930000 - 0x7393f000     C:\Program Files\Java\jdk1.7.0\jre\bin\nio.dll
0x04990000 - 0x049e5000     C:\Users\nbarraille\AppData\Local\Temp\jna3666290841889849729.dll

VM Arguments:
jvm_args: -Djava.library.path=C:\Windows\System32 -Dfile.encoding=Cp1252 
java_command: com.nbarraille.jspotify.main.Test
Launcher Type: SUN_STANDARD

Environment Variables:
PATH=C:/Program Files/Java/jdk1.7.0/bin/../jre/bin/client;C:/Program Files/Java/jdk1.7.0/bin/../jre/bin;C:/Program Files/Java/jdk1.7.0/bin/../jre/lib/i386;C:\Windows\System32
USERNAME=nbarraille
OS=Windows_NT
PROCESSOR_IDENTIFIER=x86 Family 6 Model 23 Stepping 10, GenuineIntel



---------------  S Y S T E M  ---------------

OS: Windows 7 Build 7600 

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 23 stepping 10, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1

Memory: 4k page, physical 3624108k(885020k free), swap 7246452k(3637664k free)

vm_info: Java HotSpot(TM) Client VM (21.0-b01) for windows-x86 JRE (1.7.0-ea-b129), built on Feb 10 2011 07:43:39 by "java_re" with unknown MS VC++:1600

time: Mon Mar 07 14:25:08 2011
elapsed time: 0 seconds

EDIT: *用 C 语言测试 API 的代码*

#include "api.h"


/* --- Data --- */
const uint8_t g_appkey[] = {/*My appkey*/};


/* ---------------------------  SESSION CALLBACKS  ------------------------- */
static void logged_in(sp_session *sess, sp_error error){
    printf("logged_in() called: \n");
}

static void log_message(sp_session *sess, const char *data){
    printf("log_message() called %s : \n", data);
}

static void notify_main_thread(sp_session *sess){
    printf("notify_main_thread() called \n");
}

static sp_session_callbacks session_callbacks = {
    //.logged_in = (void*)&logged_in,
    //.notify_main_thread = (void*)&notify_main_thread,
    //.log_message = (void*)&log_message,
};

static sp_session_config spconfig = {
    .api_version = 7,
    .cache_location = "tmp",
    .settings_location = "tmp",
    .application_key = g_appkey,
    .application_key_size = sizeof(g_appkey),
    .user_agent = "jspotify",
    .callbacks = &session_callbacks,
    .userdata = NULL
};

int main(int argc, char **argv)
{
    sp_session *sp;

    const char *username = "foo";
    const char *password = "bar";

    spconfig.application_key_size = sizeof(g_appkey);


    printf("Creating session \n");

    sp_error err = sp_session_create(&spconfig, &sp);

    if(err != 0){
        printf("Error occured: %d \n", err);
        return 0;
    }

    printf("Login\n");
    sp_session_login(sp, username, password);

    Sleep(10000);
    return 0;
}

当我像这样运行它(没有回调)时,输出是:

Creating session 
Login

当我注册回调(取消注释行)时,它甚至不打印任何内容!

看起来调用回调时它不会打印任何内容,因为如果我评论sp_session_login行,仅声明notify_main_thread(这是唯一打印的)将阻止程序打印......


当你有一个像这样的 C 结构时:

struct Foo {
   Bar* bar
}

即包含指向另一个结构的指针,您的 Bar 的 JNA 实现 (class Bar extends Structure)还必须实施Structure.ByReference接口——否则 JNA 会认为struct Foo包含一个实例struct Bar而不是指向 a 的指针struct Bar,并且当 C 代码将 Bar 实例中的值解释为指针时,将导致非法内存访问。

你需要添加implements Structure.ByReference to the sp_session_callbacks class.

感谢您鼓励我查看 JNA——这太酷了!

该代码的输出是:

sp_session_create returned 0
sp_session_login returned 0
log_message() called:14:16:53.825 I [ap:1388] Connecting to AP ap.spotify.com:4070

log_message() called:14:16:54.061 I [ap:938] Connected to AP: 193.182.8.11:4070

log_message() called:14:16:54.765 E [ap:3396] Connection error:  401

进程已完成,退出代码为 0

import com.sun.jna.*;
import com.sun.jna.ptr.PointerByReference;

import java.sql.Connection;

public class JNATest {
//    static {
//        System.loadLibrary("libspotify");
//    }

    public interface JLibspotify extends Library {
        int sp_session_create(sp_session_config config, PointerByReference sess);

        int sp_session_login(sp_session session, String username, String password);
        // All the other methods defined by the API
    }

    public static class sp_session extends PointerType {

        public sp_session(Pointer address) {
            super(address);
        }

        public sp_session() {
            super();
        }
    }

    public static class sp_session_config extends Structure {
        public int api_version = 7; // The version of the Spotify API your application is compiled with.
        public String cache_location = ".";
        public String settings_location = ".";
        public Pointer application_key; // Your application key.
        public int application_key_size; // The size of the application key in bytes
        public String user_agent = "jspotify";
        public sp_session_callbacks callbacks; // Delivery callbacks for session events. NULL if not interested in any callbacks
        public Pointer userdata; // User supplied data for your application
        public boolean compress_playlists;
        public boolean dont_save_metadata_for_playlists;
        public boolean initially_unload_playlists;
    }

    public interface LoggedIn extends Callback {
        public void logged_in(sp_session session, int error);
    }

    public interface LoggedOut extends Callback {
        public void logged_out(sp_session session, int error);
    }

    public interface ConnectionError extends Callback {
        public void connection_error(sp_session session, int error);
    }

    public static class sp_session_callbacks extends Structure implements Structure.ByReference{
    public LoggedIn logged_in; // Called when login has been processed and was successful
    public LoggedOut logged_out; // Called when logout has been processded. Either called explicitly if you initialize a logout operation, or implicitly if there is a permanent connection error.
    public Callback metadata_updated; // Called whenever metadata has been updated. If you have metadata cached outside of libspotify, you should purge your caches and fetch new versions.
    public ConnectionError connection_error; // Called when there is a connection error, and the library has problems reconnecting to the Spotify service. Could be called multiple times (as long as the problem is present)
    public Callback message_to_user; // Called when the acces point wants to display a message to the user. In the desktop client, these are shown in a blueish toolbar just below the search box.
    public Callback notify_main_thread; // Called when processing needs to take place on the main thread. You need to call sp_session_process_events() in the main thread to get libspotify to do more work. Failure to do so may cause request timeouts, or a lost connections.
    public Callback music_delivery; // Called when there is decompressed audio data available.
    public Callback play_token_lost; // Music has been paused because only one account may play music at the same time.
    public Callback log_message; // Logging callback
    public Callback end_of_track; // End of track. Called when the currently played track has reached its end.
    public Callback streaming_error; // Streaming error. Called when streaming cannot start or continue.
    public Callback userinfo_updated; // Called after user info (anything related to sp_user objects) have been updated.
    public Callback start_playback; // Called when audio playback should start. For this to work correctly the application must also implement get_audio_buffer_stats(). This function is called from an internal session thread - you need to have proper synchronization. This function must never block.
    public Callback stop_playback; // Called when audio playback should stop. For this to work correctly the application must also implement get_audio_buffer_stats(). This function is called from an internal session thread - you need to have proper synchronization. This function must never block.
    public Callback get_audio_buffer_stats; // Called to query application about its audio buffer. This function is called from an internal session thread - you need to have proper synchronization! This function must never block.
}

    private static final char[] APP_KEY ={/* Appkey here**/;

    public static void main(String[] args) throws InterruptedException {
        JLibspotify lib = (JLibspotify) Native.loadLibrary("spotify", JLibspotify.class);
        sp_session_config cfg = new sp_session_config();
        Pointer ptr = new Memory(APP_KEY.length);
        ptr.write(0, toBytes(APP_KEY), 0, APP_KEY.length);
        cfg.application_key = ptr;
        cfg.application_key_size = APP_KEY.length;
        sp_session_callbacks sessCallbacks = new sp_session_callbacks();
        LoggedIn loggedInCallback = new LoggedIn() {
            public void logged_in(sp_session session, int error) {
                System.out.println("logged_in() called");
            }

        };
        ConnectionError connectionErrorCallback = new ConnectionError() {

            public void connection_error(sp_session session, int error) {
                System.out.println("connection_error() called");
            }
        };
        LoggedOut loggedOutCallback = new LoggedOut() {

            public void logged_out(sp_session session, int error) {
                System.out.println("logged_out() called");
            }
        };

        sessCallbacks.logged_in = loggedInCallback;
        sessCallbacks.connection_error = connectionErrorCallback;
        sessCallbacks.logged_out = loggedOutCallback;
        sessCallbacks.log_message = new Callback() {
            public void callback(sp_session session, String message) {
                System.out.println("log_message() called:" + message);
            }
        };
        cfg.callbacks = sessCallbacks;
        PointerByReference sessionPbr = new PointerByReference();

        int error_id = lib.sp_session_create(cfg, sessionPbr); // CRASHES HERE
        System.out.println("sp_session_create returned " + error_id);
//
        sp_session mySession = new sp_session(sessionPbr.getValue());
        error_id = lib.sp_session_login(mySession, "foo", "bar");
        System.out.println("sp_session_login returned " + error_id);
        Thread.sleep(1000);
    }

    public static byte[] toBytes(char[] key){
        byte[] b = new byte[key.length];
        for(int i =0; i < key.length; i++){
            if(key[i] > 127){
                b[i] = (byte)(key[i] - 256);
            }else{
                b[i] = (byte)key[i];
            }
        }
        return b;
    }
}

这是一个执行相同操作的 C 程序(回调较少——您需要添加更多)。它适用于 OS X,因此您可能需要更改#include。由于我在澳大利亚无法访问 Spotify,因此无法对其进行测试以查看成功登录是否会触发回调,但日志记录回调有效。

#include <stdio.h>
#include <libspotify/api.h>

void SP_CALLCONV log_message(sp_session *session, const char *data) {
        fprintf(stderr,"log_message: %s\n", data);
        fflush(stderr);
}

void SP_CALLCONV connection_error(sp_session *session, sp_error error) {
        fprintf(stderr,"connection_error: %d\n", error);
        fflush(stderr);
}

int main(int argc, char** argv) {

        static byte APP_KEY[] = {
                /*the API key */};
        static sp_session_callbacks callbacks;
        callbacks.log_message = log_message;
        callbacks.connection_error = connection_error;
        static sp_session_config cfg;
        cfg.callbacks = &callbacks;
        cfg.api_version = 7;
        cfg.cache_location = ".";
        cfg.settings_location = ".";
        cfg.user_agent = "jspotify";
        cfg.application_key = APP_KEY;
        cfg.application_key_size = sizeof(APP_KEY);

        sp_session* mySession;
        int code = sp_session_create(&cfg, &mySession);
        printf("sp_session_create returned %d\n", code);
        sp_session_login(mySession, "foo", "bar");
        printf("sp_session_login returned %d\n", code);
        sleep(10);
}

如果 C 程序调用 Java 版本没有的回调,那么 jna 的使用可能有问题——如果没有,也许需要更多地了解 Spotify 以及它何时调用回调。我同意文档似乎说成功登录将调用回调,但也许它们已经过时了?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 JNA 的 C 回调使 JRE 崩溃 的相关文章

随机推荐

  • HTML如何在网页中插入动态日期

    我有一个静态网页 没有任何动态变化 然而 客户希望将日期插入到页面内的文本中 该日期将始终是当前日期加上一天 我怎么做 使用 JavaScript 并在加载时插入日期 看一下这里的工作示例 http jsfiddle net xGDvp 这
  • 被 FoldLeft 错误困惑(在 Eclipse 和 REPL 中)

    其背景非常简单 我的假设基于 Odersky 的书 Programming in Scala 2nd Edition 第 8 5 节描述了 占位符语法 我有一个 List List Boolean 即矩形位图 我试图在其中计算值 true
  • 什么是自动覆盖索引?

    使用时EXPLAIN QUERY PLAN在 SQLite 3 中 它有时会给我输出 例如 SEARCH TABLE staff AS s USING AUTOMATIC COVERING INDEX is freelancer AND s
  • 如何将图像和录制文件保存在临时目录中?

    我想将从我的应用程序中拍摄的相机照片和视频录制存储在临时目录中的单独文件夹中一段时间 当任务完成时 他们将保存到数据库中 如何将从相机和视频录制文件中拍摄的图片保存在临时目录中的单独文件夹中 您正在寻找这个来访问缓存文件夹来存储临时文件 N
  • R:ggfortify:“自动绘图不支持 prcomp 类型的对象”

    我正在尝试使用 ggfortify 来可视化我使用 prcomp 所做的 PCA 结果 示例代码 iris pca lt iris c 1 2 3 4 autoplot prcomp iris pca 错误 自动绘图不支持 prcomp 类
  • JPA Hibernate n+1 问题(Lazy 和 Eager Diff)

    我试图理解 n 1 问题 从而找到正确的解决方案 我有两个实体 公司 Entity Table name company public class Company implements Serializable private static
  • 以最小总距离连接所有点的算法

    我有一组点和适用于每对点的距离函数 我想将所有点连接在一起 总距离最小 你知道我可以使用的现有算法吗 每个点都可以链接到几个点 所以这不是通常的 推销员行程 问题 Thanks 你想要的是一个最小生成树 生成一个最常见的两种算法是 Prim
  • List 是否有协变可变版本?

    我已经将我真正想要注释的代码简化为这个最小版本 def print it numbers or nones for i number in enumerate numbers or nones if number is None numbe
  • 通过浏览器上传大文件(100 GB)

    有没有办法上传大文件 超过 80 GB 通过网络浏览器 以前我一直使用 plupload 上传文件 img png jpg 但它似乎不适用于较大的文件 我还想知道如何实现一个用户可以上传的网页 例如 Mega co nz 或 Drive g
  • context:annotation-config 是 @AutoWired 的替代品吗?

    我可以这样说吗 context annotation config在我的 XML 配置中 它会自动注入 bean 类而不需要任何注释 因此 不要使用这些注释类型 public class Mailman private String nam
  • Flask-Restless 转储 Flask-Sqlalchemy 中的十进制值

    我有这个使用 Flask SQLAlchemy 的模型 class Menu Document db Model id db Column db Integer primary key True autoincrement True nam
  • 如何通过home-brew m1 mac安装anaconda

    我刚买了一台 m1 Mac 并使用 home brew 安装了 anaconda brew install anaconda 看起来它工作得很好 除了当我真正去使用 anaconda 并输入 conda 时 我得到了可怕的 conda 命令
  • 在 Python 中求解具有时滞的 ODE

    任何人都可以给我一些建议 如何解决Python中实现了时间延迟的ODE 我似乎无法弄清楚如何使用 scipy integrate odeint 来做到这一点 我正在寻找的内容应该如下所示 the constants in the equat
  • 如何在控件中嵌入 firemonkey 表单?

    我尝试在滚动框中嵌入表单 procedure TfrmMain FormCreate Sender TObject var Control TControlView begin Control TControlView Create Sel
  • 用 Emacs 替换正则表达式

    我正在尝试做一个搜索并用正则表达式替换 假设我有一个foreach foo1 txt foo2 txt foo3 txt foo4 txt 我想在列表中的每个项目周围加上 我认为 从文档 这个正则表达式可以工作 foo 1 4 txt gt
  • glmnet 如何计算最大 lambda 值?

    The glmnet包使用了一系列LASSO调整参数lambda从最大缩放lambda max在此情况下不选择预测变量 我想知道如何glmnet计算这个lambda max价值 例如 在一个简单的数据集中 set seed 1 librar
  • 如何使用正则表达式前瞻来限制输入字符串的总长度

    我有这个正则表达式 想要添加限制总长度不超过 15 个字符的规则 我看到了一些前瞻示例 但它们不太清楚 你能帮我修改这个表达式以支持新规则吗 A Z A Z 既然您在标题中提到了这一点 那么对您的案例的负面展望将是 16 regex goe
  • Ruby 中重做和重试语句的用途是什么?

    我能想到的唯一用例redo适用于写入套接字或从数据库读取等操作 但如果这些操作失败一次 后续尝试很可能也会失败 所以对我来说这仍然有点毫无意义 至于retry我真的想不出它会有什么用处 这对我来说似乎毫无意义 因为我不知道也不使用 Ruby
  • CanExecuteCommand 对性能有影响吗?

    使用 ICommand 对象的 CanExecuteCommand 对性能有何影响 该方法是否一遍又一遍地执行 我需要迭代大约 200 个对象的集合 根据这些对象决定是否应启用绑定到命令的按钮 CanExecuteCommand 是否会重复
  • 使用 JNA 的 C 回调使 JRE 崩溃

    我在 JNA 中处理回调时遇到问题 我正在尝试使用 C API 它使用回调来处理多个会话事件 登录 注销 连接问题 会话对象 称为sp session 是一个不透明的结构 所有回调都注册在sp session callbacks结构 根据