JNI Structure Alignment

a 夏天 提交于 2019-12-13 06:15:50

问题


I'm calling a DLL compiled with the VisualStudio 2005 with the "#pragma pack(1)" setting. So the structure alligment (SA) is without padding for fast data access [1]. I think the JVM is compiled with normal structure alligment [2].

So I want to know what are my options? The call to the dll(I'm not in Codecontrol) is going through a wrapper dll (I'm in Codecontrol).

  1. Can I call out of the Wrapper a dll with another SA setting? So that the Wrapper-Dll, which is called from Java uses the normal SA setting and calls a dll which is compiled with #pragma pack(1) set.
  2. Is it possible to do a setting in JNI to call dlls with #pragma pack(1) set?
  3. I also could use JNA. Is there a possibility to do such an setup.

[1] #pragma pack effect

[2] http://www.velocityreviews.com/forums/t128433-jni-with-1-byte-alignment-crashes-jvm.html


回答1:


#pragma pack affects how the compiler treats code until it sees another #pragma pack or a #pragma pop, so you can have as many different structures with different alignment as you need. As long as you don't have a pack setting when you include jni.h you should be fine. The easiest way to ensure that is to include the JNI headers before you include any of your structure definitions with custom alignment.

JNA explicitly provides a structure alignment of "none" which maps to #pragma pack(1), and it may be set for an entire library (i.e. all structures defined within that library interface):

interface MyLibrary extends Library {
    int STRUCTURE_ALIGNMENT = Structure.ALIGN_NONE;
}

Or you can set it for an individual structure:

class MyStructure extends Structure {
    public MyStructure() {
        super(ALIGN_NONE);
    }
}



回答2:


The #pragma pack directive is intended to locally "overwrite" the /Zp compiler option. It means that a Dll compiled with some /Zp[n] option can still use structure requiring a different aligment, provided that the structure declarations are enclosed with #pragma pack.

Example:

One Header

// lib.h, structure must be 1 byte aligned
struct lib {
    char ch;
    void * p;
};

Source using the lib, compiled with /Zp4

// user.cpp
#pragma pack(push, 1) // force 1 byte for the header, save current value
#include "lib.h"
#pragma pack(pop)    // restore saved structure aligment


来源:https://stackoverflow.com/questions/19856048/jni-structure-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!