How to call a C/C++ function from a Java method

Here is a brief explanation of how to call a c or c++ function from a java method. I am using Visual C++. Any edition from Visual C++ 6.0 to 2019 will work!
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Here is a brief explanation of how to call a c or c++ function from a java method. I am using Visual C++. Any edition from Visual C++ 6.0 to 2019 will work!

Step 1 - Create a C++ DLL Project

Proceed like so [see the video at the end of this page for a detailed explanation]:

// Project name is "CPPInterop" 
// dllmain.cpp : entry point. 
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD  ul_reason_for_call,
LPVOID lpReserved
)
{

  switch (ul_reason_for_call)
  {

  case DLL_PROCESS_ATTACH:
  case DLL_THREAD_ATTACH:
  case DLL_THREAD_DETACH:
  case DLL_PROCESS_DETACH:
    break;

  }

  return TRUE;

}

#include <cstdio>

extern "C"
{

  __declspec (dllexport) void __stdcall Java_CMyClass_myMethod()
  {

    printf("Hello from C++");

  }

}

Step 2 - Java Project

Here is the Java class that has "myMethod" written as a native call.

public class CMyClass
{

  // native declaration 
  public native void myMethod();

  static 
  {

    System.loadLibrary("CPPInterop");

  }

  public static void main(String[] args)
  {

    // call the method 
    new CMyClass().myMethod();

  }

}

Watch this Video for Details


This Blog Post/Article "How to call a C/C++ function from a Java method" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.