Java SWIG wrapper vs direct function calling

0

I have some kind of library that I am writing wrapper for and then I am trying to generate SWIG wrapper on it so I could make calls straight from Java.

I encountered a problem which I can not debug as there are basically 0 information (Java side). Here is what I am dealing with. I have got a custom class like this:

class APIClass {

private:

public:
    APIClass();
    void mbstowcsTest();
};

And its implementation looks like this

typedef unsigned short      AName[32];

void APIClass::mbstowcsTest() {
  const char* source = "D:\\test3\\source\\test.txt";
  AName tmp1;
  mbstowcs((wchar_t*)tmp1, source, 32 - 1);
}

With such code I am generating SWIG files for it and compile the code with batch script like so:

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x64

swig -c++ -java -outdir java api.i

set CompilerFlags=-nologo -Zi
pushd build
cl %CompilerFlags% ..\api.cpp ..\api_wrap.cxx /I"C:\Program Files (x86)\Java\openjdk8u102-win_jdk\include"^
  /I"C:\Program Files (x86)\Java\openjdk8u102-win_jdk\include\win32" /LD /EHsc
popd

COPY .\build\api.dll .\java\

As for api.i interface file it is only:

%module api
%{
    #include "api.h"
%}
%include "api.h"

Basically, if I am calling APIClass::mbstowcsTest() in the C++ main function all is going well and mbstowcs() is going through without any problems like so:

APIClass *api = NULL;
api = new APIClass();
api->mbstowcsTest();

While in Java side I have:

class main {
    public static void main(String[] args) {
        System.loadLibrary("api");
        APIClass api = new APIClass();
        api.mbstowcsTest();
    }
}

The problem in Java code is that whenever code reaches mbstowcs() in APIClass::mbstowcsTest() all I am getting is outputs like Process finished with exit code -1073740791 (0xC0000409). Could anyone tell me why is that a problem? I tried using other functions from stdlib.h like abs() and it worked.

java
c++
visual-c++
java-native-interface
swig
asked on Stack Overflow Oct 3, 2018 by Lisek

1 Answer

0

Turned out that it is essential to use the same compiler flags as in Visual Studio 2013 compilation. Therefore the batch script should look at least as:

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x64

swig -c++ -java -outdir java api.i

set CompilerFlags= /Zi /nologo /W3 /WX- /sdl /Od /Oy-^
    /D WIN32 /D _DEBUG /D _CONSOLE /D _LIB /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE^
    /D _UNICODE /D UNICODE^
    /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd /LD

pushd build
cl %CompilerFlags% ..\api.cpp ..\api_wrap.cxx /I"C:\Program Files (x86)\Java\openjdk8u102-win_jdk\include"^
  /I"C:\Program Files (x86)\Java\openjdk8u102-win_jdk\include\win32"
popd

COPY .\build\api.dll .\java\

Now everything works just as fine

answered on Stack Overflow Oct 4, 2018 by Lisek

User contributions licensed under CC BY-SA 3.0