How can I use javacpp reach the class like class #define XXX{}? - javacpp

part of c++ code :
class CTB_DLL ctb::Terrain {
public:
/// Create an empty terrain object
Terrain();
/// Instantiate using terrain data on the file system
Terrain(const char *fileName);
/// Read terrain data from a file handle
Terrain(FILE *fp);
/// Read terrain data from the filesystem
void
readFile(const char *fileName);
/// Write terrain data to a file handle
void
writeFile(FILE *fp) const;
}
java code:
#Platform(include = "TerrainTile.hpp")
#Namespace("ctb")
public class TerrainTile {
public static class Terrain extends Pointer{
public Terrain() { allocate();}
public native void allocate();
public native void Terrain();
//to call the basic methods
/* public native void Terrain(Pointer filename);
public native void readFile(#Const Pointer filename);
public native void writeFile();*/
}
public static void main(String[] args) {
TerrainTile terrain = new TerrainTile();
}
}
when i using cmd : java -jar javacpp-1.5.5.jar TerrainTile.java
error occur:
Exception in thread "main" java.lang.ClassNotFoundException

Related

When attaching agent to running process, bytebuddy transformer doesn't seem to take effect

The code of my program to be attached is as below.
public class Foo {
}
public class TestEntry {
public TestEntry() {
}
public static void main(String[] args) throws Exception {
try
{
while(true)
{
System.out.println(new Foo().toString());
Thread.sleep(1000);
}
}
catch(Exception e)
{}
}
}
What I attempt to do is to make Foo.toString() returns 'test' by using the following agent.
public class InjectionAgent {
public InjectionAgent() {
}
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
public static void premain(String args, Instrumentation inst) throws Exception
{
System.out.println("premain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
}
I notice that, it was successful when I using -javaagent way, whereas attach way failed, here is code for attach.
public class Injection {
public Injection() {
}
public static void main(String[] args) throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException, InterruptedException {
VirtualMachine vm = null;
String agentjarpath = args[0];
vm = VirtualMachine.attach(args[1]);
vm.loadAgent(agentjarpath, "This is Args to the Agent.");
vm.detach();
}
}
I tried to add AgentBuilder.Listener.StreamWriting.toSystemOut() to the agent, after attaching, the output of TestEntry shows
[Byte Buddy] DISCOVERY Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] TRANSFORM Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] COMPLETE Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
Foo#7f31245a
Foo#6d6f6e28
Foo#135fbaa4
Foo#45ee12a7
Foo#330bedb4
==================================Update=====================================
I defined a public method 'Bar' in Foo like this
public class Foo {
public String Bar()
{
return "Bar";
}
}
and then I was trying to make Foo.Bar() returns "modified" in the following way:
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
premain(args, inst);
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges()
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.visit(Advice.to(InjectionTemplate.class).on(ElementMatchers.named("Bar")));
}
})
.installOn(inst);
}
static class InjectionTemplate {
#Advice.OnMethodExit
static void exit(#Advice.Return String self) {
System.out.println(self.toString() + " " + self.getClass().toString());
self = new String("modified");
}
}
but I got this error:
java.lang.IllegalStateException: Cannot write to read-only parameter class java.lang.String at 1
any suggestions?
It does not seem like you are using redefinition for your agent. You can activate it using:
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges();
The last part is required on most JVMs (with the notable exception of the dynamic code evolution VM, a custom build of HotSpot). It tells Byte Buddy to not add fields or methods, what most VMs do not support.
In this case, it is no longer possible to invoke the original implementation of a method what is however not required for your FixedValue. Typically, users of Byte Buddy take advantage of Advice when creating an agent that applies dynamic transformations of classes.

About Singleton class

package com.java2novice.algos;
public class MySingletonExample {
private static MySingletonExample myObjct;
static{
myObjct = new MySingletonExample();
}
private MySingletonExample(){
}
public static MySingletonExample getInstance(){
return myObjct;
}
public void runMe(){
System.out.println("Hey, it is working!!!");
}
public static void main(String [] args){
MySingletonExample mse = getInstance();
ms.runMe();
}
}
Can anyone please give a description of the above program why static is used here and why provide a static method to get instance of the object ?

NinJect Get Service is not returning an instance of the class

I am working with MVC 4.0 & .net 4.0 and wish to use Ninject.
I have a static class, in which objects are created. I can NOT make the static calling class non-static!
I am trying to get an instance based on this binding
Bind<ClinicWebsite.ViewModels.ISelectionEngine>)
.To<ClinicWebsite.ViewModels.Genric_SelectionEngine>();
in the static class I call:
ClinicWebsite.ViewModels.Generic_SelectionEngine myService =
ClinicWebsite.App_Start.NinjectWebCommon.Kernel
.GetService(typeof(ClinicWebsite.ViewModels.ISelectionEngine))
as ClinicWebsite.ViewModels.Generic_SelectionEngine;
but when I examine "myservice" I get:
The name 'myservice' does not exist in the current context
What could I be doing wrong, or is there another way to explicitly create an instance with Ninject (again, cannot get rid of static calling class)
NinjectWebCommon
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
private static readonly StandardKernel kernel = new StandardKernel();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
//DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
Bind<ClinicWebsite.ViewModels.ISelectionEngine>().To<ClinicWebsite.ViewModels.Generic_SelectionEngine>();
}
public static IKernel Kernel
{
get
{
return kernel;
}
}
}
I found the answer.
because this is in a static class I need to make"myservice" a static member of the class and then assign to it.

Java crashes when calling dll function using JNA

I'm using JNA to run a dll function:
Here is all the code corresponding to that manner:
The Native Declarations:
//how the method declared
H264_Login (char *sIP, unsigned short wPort, char *sUserName, char *sPassword, LP_DEVICEINFO lpDeviceInfo, int *error, ,SocketStyle socketTyle=TCPSOCKET); // where LP_DEVICEINFO is a struct
//how the struct declared
typedef struct _H264_DVR_DEVICEINFO
{
SDK_SYSTEM_TIME tmBuildTime; // the "SDK_SYSTEM_TIME" is another struct
char sSerialNumber[64];
int byChanNum;
unsigned int uiDeviceRunTime;
SDK_DeviceType deviceTye; // the "SDK_DeviceType" is a enum
}H264_DVR_DEVICEINFO,*LP_DEVICEINFO;
// this is how "SDK_SYSTEM_TIME" is defined
typedef struct SDK_SYSTEM_TIME{
int year;
int month;
int day;
}SDK_SYSTEM_TIME;
// this is how "SDK_DeviceType" is defined
enum SDK_DeviceType
{
SDK_DEVICE_TYPE_DVR,
SDK_DEVICE_TYPE_MVR,
SDK_DEVICE_TYPE_NR
};
// this is how "SocketStyle" is defined
enum SocketStyle
{
TCPSOCKET=0,
UDPSOCKET,
SOCKETNR
};
The following is their corresponding Java mappings:
public class Test implements StdCallLibrary {
public interface simpleDLL extends StdCallLibrary {
long H264_Login(String sIP, short wPort, String sUserName, String sPassword,
Structure DeviceDate, int error, int TCPSOCKET);
}
static
{
System.loadLibrary("NetSdk");
}
// the struct implementation
public static class DeviceDate extends Structure{
public SDK_SYSTEM_TIME tmBuildTime;
public String sSerialNumber;
public IntByReference byChanNum;
public IntByReference uiDeviceRunTime;
public IntByReference deviceTpye;
#Override
protected List<Object> getFieldOrder() {
List<Object> list = new ArrayList<>();
list.add("tmBuildTime");
list.add("sSerialNumber");
list.add("byChanNum");
list.add("uiDeviceRunTime");
list.add("deviceTpye");
return list;
}
}
public static class SDK_SYSTEM_TIME extends Structure{
public IntByReference year;
public IntByReference month;
public IntByReference day;
#Override
protected List<Object> getFieldOrder() {
List<Object> list = new ArrayList<>();
list.add("year");
list.add("month");
list.add("day");
return list;
}
}
// and then how I called it through the main function
public static void main(String args[]) throws FileNotFoundException{
simpleDLL INSTANCE = (simpleDLL) Native.loadLibrary( ("NetSdk"), simpleDLL.class);
DeviceDate dev = new DeviceDate() // where DeviceDate is a static class inherits com.sun.jna.Structure
int err = (int) INSTANCE.H264_GetLastError();
long result = INSTANCE.H264_Login("255.255.255.255", (short) 33333, "admin", "admin", dev, err, 0);
}
}
upon running the app, the Java crashes:
and this is the full problem signature:
Problem signature:
Problem Event Name: APPCRASH
Application Name: javaw.exe
Application Version: 7.0.600.19
Application Timestamp: 536a95c6
Fault Module Name: jna3976113557901128571.dll
Fault Module Version: 4.0.0.215
Fault Module Timestamp: 52d3949a
Exception Code: c0000005
Exception Offset: 0000e3a2 OS
Version: 6.1.7601.2.1.0.256.1
Locale ID: 1033
Additional Information 1: 7bc2
Additional Information 2: 7bc24d73a5063367529b81d28aecc01c
Additional Information 3: 5bea
Additional Information 4: 5beaa1c0441c3adb156a170a61c93d19
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our
privacy statement offline: C:\Windows\system32\en-US\erofflps.txt
Your mappings have a number of errors. Your structures should look like the following (IntByReference represents places where you would pass the address of an int, and you can't substitute String for a primitive native char array). Please refer to the JNA mapping documentation to ensure you understand how native types map to Java types:
public static class LP_DEVICE_INFO extends Structure{
public SDK_SYSTEM_TIME tmBuildTime;
public byte[] sSerialNumber = new byte[64];
public int byChanNum;
public int uiDeviceRunTime;
public int deviceType; // Assuming the size of the enum is int
#Override
protected List<Object> getFieldOrder() {
List<Object> list = new ArrayList<>();
list.add("tmBuildTime");
list.add("sSerialNumber");
list.add("byChanNum");
list.add("uiDeviceRunTime");
list.add("deviceTpye");
return list;
}
}
public static class SDK_SYSTEM_TIME extends Structure{
public int year;
public int month;
public int day;
#Override
protected List<Object> getFieldOrder() {
List<Object> list = new ArrayList<>();
list.add("year");
list.add("month");
list.add("day");
return list;
}
}

Implementation of custom Writable in Hadoop?

I have defined a custom Writable class in Hadoop, but Hadoop gives me the following error message when running my program.
java.lang.RuntimeException: java.lang.NullPointerException
at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:115)
at org.apache.hadoop.io.SortedMapWritable.readFields(SortedMapWritable.java:180)
at EquivalenceClsAggValue.readFields(EquivalenceClsAggValue.java:82)
at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeserializer.deserialize(WritableSerialization.java:67)
at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeserializer.deserialize(WritableSerialization.java:40)
at org.apache.hadoop.mapred.Task$ValuesIterator.readNextValue(Task.java:1282)
at org.apache.hadoop.mapred.Task$ValuesIterator.next(Task.java:1222)
at org.apache.hadoop.mapred.Task$CombineValuesIterator.next(Task.java:1301)
at Mondrian$Combine.reduce(Mondrian.java:119)
at Mondrian$Combine.reduce(Mondrian.java:1)
at org.apache.hadoop.mapred.Task$OldCombinerRunner.combine(Task.java:1442)
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.sortAndSpill(MapTask.java:1436)
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.flush(MapTask.java:1298)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:437)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1136)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
Caused by: java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.hash(ConcurrentHashMap.java:332)....
EquivalenceClsAggValue is the name of the Writable class I've defined and this is my class:
public class EquivalenceClsAggValue implements WritableComparable<EquivalenceClsAggValue>{
public ArrayList<SortedMapWritable> aggValues;
public EquivalenceClsAggValue(){
aggValues = new ArrayList<SortedMapWritable>();
}
#Override
public void readFields(DataInput arg0) throws IOException {
int size = arg0.readInt();
for (int i=0;i<size;i++){
SortedMapWritable tmp = new SortedMapWritable();
tmp.readFields(arg0);
aggValues.add(tmp);
}
}
#Override
public void write(DataOutput arg0) throws IOException {
//write the size first
arg0.write(aggValues.size());
//write each element
for (SortedMapWritable s:aggValues){
s.write(arg0);
}
}
I wonder to know what is the source of the problem.
Looks like an error in your write(DataOutput) method:
#Override
public void write(DataOutput arg0) throws IOException {
//write the size first
// arg0.write(aggValues.size()); // here you're writing an int as a byte
// try this instead:
arg0.writeInt(aggValues.size()); // actually write int as an int
//..
Look at the API docs for DataOutput.write(int) vs DataOutput.writeInt(int)
I'd also amend your creation of the SortedMapWritable tmp local variable in readFields to use ReflectionUtils.newInstance():
#Override
public void readFields(DataInput arg0) throws IOException {
int size = arg0.readInt();
for (int i=0;i<size;i++){
SortedMapWritable tmp = ReflectionUtils.newInstance(
SortedMapWritable.class, getConf());
tmp.readFields(arg0);
aggValues.add(tmp);
}
}
Note for this to work, you'll also need to amend you class signature to extend Configurable (such that Hadoop will inject a Configuration object when your object is initially created):
public class EquivalenceClsAggValue
extends Configured
implements WritableComparable<EquivalenceClsAggValue> {