Transitioning from java to C++ - java

Based both on when the languages were invented and the structure of the languages, this transition is probably meant to go the other way, but I am fairly confident in my java abilities, or at least I am good enough at it.. but I am trying to now go to C++, and I am having difficulties.
In java, reading a text file could be done by declaring a new file object, and then a scanner, (or some like class) to read it, or the reader classes, (buffered reader, input stream reader, file reader... the list of variations continues) But now I am trying to do that in C++, a very basic function of a program, and my code is not working. The code I have is:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "This text appears in the file.\n";
myfile.close();
return 0;
}
what am I forgetting? It seems complete to me, but then again, I know hardly any C++...

That code is correct. Are you sure the example.txt file isn't being created? For example, if you are using visual studio then it won't be in the Debug or Release folders but will show up one level up since that is what the working directory will be by default.

I assume your real question is how to learn C++ when already familiar with Java. For this I would recommend the book Accelarated C++. It's a very good introduction to C++. However, it is dense and will require some study. It took me about two months to work though it.
If you don't have the time or motivation for that you could start with Effective C++. It's basically a collection of do's and don'ts that will help you avoid the common beginner mistakes.

Java baggage is a liability, not an asset. Thinking in C++ you would make this code both simpler and safer:
#include <fstream>
int main () {
std::ofstream myfile("example.txt");
myfile << "This text appears in the file.\n";
return 0; // you can skip this too
}
Or even shorter:
#include <fstream>
int main () { std::ofstream("example.txt") << "This text appears in the file.\n";}

Related

keyword in java which is similar to define in C [duplicate]

This question already has answers here:
Can I have macros in Java source files
(9 answers)
Closed 6 years ago.
In C i used to use #define p printf
to help me code easily rather than typing printf every time
let me give an example to understand better
p("hello world");
it does the job of
printf("hello world");
There is a way in java to do this I went through it long back Its not a duplicate question as they answered there is no way Iam sure of there is a way to do this using ENUM
How can I implement this in java
You need to use a method in a helper class.
e.g.
enum Helper {;
static void p(String fmt, String... args) { System.out.printf(fmt, args); }
static void p(Number n) { System.out.print(n); }
}
so you can call
import static mypackage.Helper.p;
p("hello world");
There is no scanf though you can use a Scanner to do something similar.
Most of the useful things you can do with macros, you can do with simple Java syntax. In term the JIT will optimise the code at runtime to get the same performance benefits.
Simple answer: you don't. Java doesn't have that kind of text substitution.
Actually, you shouldn't be making those types of substitutions in C, either. A #define like that is a recipe for trouble.
For the love of god. Don't do this. You'll have a lot of unexpected behavior in your code.
However you could learn some shortcuts like typing "syso" + Return (in Eclipse) or "sout" +Return (in Netbeans). Does not shorten your code, but it's faster.
There is no similar macro available in Java. You could write your own methods that delegate to System.out.ṕrintln and the likes, but it would probably be unnecessary work for very little gains.
Think of it this way, typing out those words will make your fingers nimbler.

Using DLL's written in C# from Java

This is my first time working with DLL's and I am at a bit of a loss.
Not because I don't understand the code. But because all of the tutorials Im following and they are breaking at some points.
First I attempted this, but my work was cut short when the javah command would not work erroring out with the message: Error: Could not find or load main class com.sun.tools.javah.Main
I then moved on to make my own ddl's so that I can call them from C a library. Found this video and I was able to follow it and its page on the Microsoft page to make the dll. Note that I am fully capable of following the example. The one part that I struggle with is what happens if I don't have the header file or a lib file to the DLL. So then I started following this example and visual studios is saying that import my not exist.
I found that others were able to get the same exact thing working.
What am I doing wrong? End goal, I'd like to know how to create a DLL file like in the video. And only with the DLL file in my possession, access its functions.
So if the DLL was created with the following:
Header
namespace nmspace
{
class myclass{
public:
static __declspec(dllexport) void Crap();
};
}
Source.cpp
#include "Header.h"
using namespace std;
#include <iostream>
namespace nmspace
{
void myclass::Crap(){
cout << "Some Crap";
}
}
How would I call it via LoadLibarary or LoadLibararyA. Note that this did not work for me
To read the dll:
#include <Windows.h>
#include <iostream>
using namespace std;
void PrintFullPath(char * partialPath)
{
char full[_MAX_PATH];
if (_fullpath(full, partialPath, _MAX_PATH) != NULL)
printf("Full path is: %s\n", full);
else
printf("Invalid path\n");
}
int main(){
HMODULE hMod = LoadLibrary("SimpleDLL.dll");
if (NULL == hMod)
{
cout << "LoadLibrary failed\n";
PrintFullPath(".\\");
system("PAUSE");
return 1;
}
}
In the above code, I print out the current working directory. In that directory I have placed my dll. Still the dll is not being loaded.
I am using Visual Studios if that matter. I would also be intrested to see how I would compile the above c++ code via command line and include the dll with it!
EDIT:
I also found this but it relys on the header file as well. Note that I will know what the function names and formats are through the documentation. I just have no header file!
DLLs created with C# are not like other DLLs. They are technically called .NET assemblies. They rely on the Common Language Runtime (CLR) in the same way that Java bytecode relies on the Java Virtual Machine. The video you posted a link to is not creating a .NET assembly, but rather a native Windows DLL.
Obviously, if you have two virtual machines loaded in a process, things are going to get complicated. They both have their own ideas about how to use memory, garbage collection, layout of objects in memory, threading and so on.
That's not to say that what you are trying to do is impossible, but it's a lot more complicated than loading native libraries with LoadLibrary.
You might like to take a look at the following projects to help you out:
SWiG - www.swig.org - free but I'm not sure how much extra work will be involved in interfacing Java to C#
JNbridge - www.jnbridge.com - not free but claims to make what you are trying to do simple
Javonet - www.javonet.com - not free but claims to make what you are trying to do simple
IKVM - www.ikvm.net - this one is a bit left-field. It lets you run Java bytecode on a .NET runtime, which then means that you can call .NET/C# code directly. If you Java is fairly simple and/or you don't have to deploy your code to many clients, this might work for you.

JavaCV examples/tutorial

There are a lot of books about OpenCV C++, many examples and etc. But I can't find that on Java. I know the basics like reading, showing images, grabbing frames and displaying them in the loop, but it's so little. I want to do ComputerVision, but all I can find about JavaCV on google are things I mentioned before. Where/How I can learn it?
The java wrapper is quite young, so there are not many examples on the web. You should get a little understanding of C++ (if you have not already), and use the C++ examples. Many classes/methods are available in the java wrapper, so you can translate them easily.
Sometimes it is a bit difficult to find the appropriate java statement. E.g., all the constants, or the public functions defined in the class Core are directly available in C++ due to the #include statement. In Java, these are public static functions from the class Core, so you have to write Core.xy().
To find the class where a specific constant, or public function is defined, I like to use the javadoc index. So, if you want to know where the function absdiff is, you search for this string in that index, and find out that it is a static method of Core, so Core.absdiff(x, y, z) is the java statement for the C++ statement absdiff(x, y, z).

How do I call a C Function from a Jython script?

I am creating a GUI using Jython. I want to program my logic in C. How could I can call a C Function from my Python Code. Sorry if this a newbie question, but I have never worked with linking files except Sparc Assembly from C.
Jython cannot use ctypes, or C extension modules (whether built manually, or with Cython, or otherwise).
The way to do this is the same way as in Java: Through a JNI bridge.
First, you write a C++ wrapper that talks to the so, and uses functions from <jni.h> to implement functions like this:
JNIEXPORT void JNICALL _PACKAGE(bar)(JNIEnv *env, jclass cls, jint i) {
if (bar(i)) {
throwPyFromErrno(env, OSError);
}
}
Next, in Java, you define a public class full of Java wrappers around those C++ wrappers, like this:
public class foo implements InitModule {
public final static native void bar(int i);
}
Finally, in Jython, you can just import the class (which acts like a Python module) from its Java module and use it like any other module:
try:
foo.bar(3)
except OSError as e:
print "Failed:", e
Most of this is standard JNI, but you also have to know things like how to create Jython objects. Ideally, you'll use wrappers for that, so you can just write makePyInteger(env, value) or throwPyFromErrno(env, exctype) instead of doing all the FindClass, GetStaticMethodID, etc. stuff manually.
I don't have any tutorials to recommend. But see jnios for a nice-sized example. The O'Reilly book's Chapter 25. Extending and Embedding Jython seems like it might be a decent primer (although I haven't read it). You'll probably want to read a tutorial on using JNI for Java before trying to tackle Jython.
A different way to solve this problem is to break your single program into two pieces.
The GUI program runs in Jython. When it needs to call the C code, it does that by running a worker program.
The worker program runs in CPython or PyPy, so it can use any of the usual techniques for talking to C libraries: ctypes, cffi, a custom C extension module (maybe using Cython, Boost.Python, SWIG, SIP, …), Weave, etc.
For a simple case, where you just need to call one function, pass it a few strings, and get back a string, it's as trivial as this:
import subprocess
def my_function(*args):
return subprocess.check_output(['python',
'/path/to/worker/script.py'] + args)
(Note that there are a few bugs with subprocess in older versions of Jython, especially on OS X and Windows. If you run into a problem, 2.5.4 and 2.7.0, which are currently in RC and beta stages, respectively, have probably fixed it.)
If you need to make lots of calls one at a time throughout the life of your program, you'll probably want to keep the worker script running in the background, and use some form of RPC to talk to it. This blog post shows how to do it using the bjsonrpc library.

How do you #include files in Java?

Coming from a C++ environment I got used to splitting up many of the functions that I needed into an funcs.h file and then do #include "funcs.h" and then adding the functions prototypes into the main .cpp file.
Now I am starting to work with Java (mainly with Minecraft ModloeaderMp), and I already made a funcs.java file where there are some premade functions (e.g., some functions for file copying, giving stacks of items, etc.). Since I am already using the statement Public class mod_mine extends BaseModMp, is there a way I can import the functions or do I can I just do another Public class mod_mine extends funcs?
You don't #include in Java; you import package.Class. Since Java 6 (or was it 5?), you can also import static package.Class.staticMethodOfClass, which would achieve some forms of what you're trying to do.
Also, as #duffymo noted, import only saves you from systematically prefixing the imported class names with the package name, or the imported static method names with the package and class name. The actual #include semantics doesn't exist in Java - at all.
That said, having a "funcs.java" file seems to me like you are starting to dip your toes into some anti-patterns... And you should stay away from these.
There's no #include in Java.
I would not like a design that had a funcs.java that stored all the variables. Objects are state and behavior encapsulated into a single component. You aren't designing in an object-oriented way if you do that.
Good names matter. A class named Stuff that extends Stuff2 had better just be a poor example.
That's not good Java. I wouldn't consider it to be good C++, either.
It sounds like you're putting all your methods in the same class. You should separate them:
Utility classes
These should contain static methods that do things like get the contents of a file, show a dialog screen, or add two numbers together. They don't really belong in an object class, they don't require instances, and they're used widely throughout the program. See java.lang.Math for a good example of this.
Constant class or configuration files
This can be a Constants class that contains static final members, like PI = 3.1415. You can access them using Constants.PI.
Or, you can use configuration files and load them into Configuration and access the configuration variables with something like config.get("database").
Other
If your code doesn't fit into any of these, you will want to put it into some class such that your code fits object-oriented programming concepts. From your question, it sounds like you'll want to read up on this. I would first read Head First Java, then maybe some other books on object-oriented programming in Java. After that, I'd look at some design patterns.
Java is an object-oriented programming language, and there is a reason for it.
There isn't any #include in Java, although you can import classes from other packages.
Making separate class, func.java, to store variables might not be a good idea, until or unless all of them are constants.
By extending some class, you can reuse the function. But does extending class pass the is a test? If not that, this might be a bad idea.
If moving from C++, going through some good book, for example, Head First Java might help a lot.
There isn't any #include in Java. You can use the import statement to make classes and interfaces available in your file.
You can run the C preprocessor on a Java file, ensuring you use the -P flag to disable line annotations. A quick Google search confirms that this has been attempted at least twice, and is even used in the popular fastutil library:
Using C style macros in Java
https://lyubomyr-shaydariv.github.io/posts/2016-09-06-fun-with-java-and-c-preprocessor/
This works for all directives (#include, #define, #ifdef, and so forth) and is both syntactically and semantically identical to the equivalent statements in C/C++.
Actually... There is a way to have the same semantics as in C's #include (the keyword was later borrowed by C++ for the sake of looking fancy...). It's just not defined with the same words, but it does exactly what you are looking for.
First, let's see what you do with #include in C++ to understand the question:
include #defines,
"forward" function definitions (their "body" being defined elsewhere, in a class implementation, if you remember Turbo Pascal, you get my point),
define structures,
and that's pretty much it.
For the structure definitions, there isn't any point. That's old-school C: in C++ you don't define struct {} anymore for ages; you define class structures with properties and accessor methods. It's the same in Java: no typedef struct {} here either.
For this, you have the "interface" declaration (see Interfaces (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)):
It does exactly what you're looking for:
public interface MyDefines {
final CHAR_SPACE : ' '; // ugly #define
int detectSpace(FileInputStream fis); // function declaration
// and so on
}
Then, to use:
public class MyClass extends MyAncestor implements MyDefines {
...
// implementation of detectSpace()
int detectSpace(FileInputStream fis) {
int ret = 0;
char Car;
if((Car = fis.read()) != -1) && (Car == CHAR_SPACE)) ret++;
...
}
Read the link given above; it's full of useful cases.

Categories