Solved

Calling C library from C++ program

Posted on 2014-02-21
1
430 Views
Last Modified: 2014-03-05
I have C++ based java native methods that works perfectly in passing String parameters back and forth with Java but wanted to know how could i load the C library from this C++ program and pass the parameters into it and get return string back from it.

The reason I want to not interact with C directly is because I need to pass 32 string parameters and handling them may be a challenge. If there is a easy way to handle 32 parameters in C  that will be great.
0
Comment
Question by:jgdvishnu
1 Comment
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 39877819
You can call C libraries from C++ code just like other C++ libraries. E.g.

// lib.h

size_t get_string(char* buf, const size_t bufsz);

Open in new window


// lib.c

size_t get_string(char* buf, const size_t bufsz) {

  const char* pText = "This is my output";
  size_t len = strlen(pText);

  if (len  + 1 > bufsz) return 0; // not enough room

  strcpy(buf,pText);

  return len;
}

Open in new window


//usingclib.cpp
#include "lib.h"
#include <string>
#inlude <iostream>
// ...

  char str[255];
  std::string string_from_c_lib;

  if (0 < get_text(str,sizeof(str)) {

    string_from_c_lib = str;

    std::cout << "Got that from C lib: " << string_from_c_lib << std::endl;
  }

Open in new window

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now