Solved

Calling C library from C++ program

Posted on 2014-02-21
1
428 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 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

13 Experts available now in Live!

Get 1:1 Help Now