I am currently developing on a Chromium Embedded framework app.
The project consists of a client and a helper. I need to know the bundle path from the helper, easy just use the methods of foundation.... Well I can't since I can't use foundation in the helper.
The client is a C++ based core wrapped in a objective-c++ cocoa app.
The helper is pure C++.
The two apps share an custom class for process-type-based behaviour ( see code below). The "OnBeforeCommandLineProcessing" method needs to use the bundle path! (Just changing file ending to .mm and importing foundation/cocoa does not work, as soon as i import foundation things turn ugly with a huge amount of errors). How can I get bundle path from C++ without foundation? This does not work: mainBundle = CFBundleGetMainBundle();
namespace client {
// Base class for customizing process-type-based behavior.
class ClientApp : public CefApp {
public:
ClientApp();
enum ProcessType {
BrowserProcess,
RendererProcess,
ZygoteProcess,
OtherProcess,
};
// Determine the process type based on command-line arguments.
static ProcessType GetProcessType(CefRefPtr<CefCommandLine> command_line);
protected:
// Schemes that will be registered with the global cookie manager.
std::vector<CefString> cookieable_schemes_;
private:
// Registers custom schemes. Implemented by cefclient in
// client_app_delegates_common.cc
static void RegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes);
void OnBeforeCommandLineProcessing(const CefString& process_type,
CefRefPtr<CefCommandLine> command_line) OVERRIDE;
// CefApp methods.
void OnRegisterCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar) OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(ClientApp);
};
} // namespace client
#endif // CEF_TESTS_CEFCLIENT_COMMON_CLIENT_APP_H_
Trying to import cocoa/foundation after renaming to .mm:
You're importing Foundation.h when you mean #include <CoreFoundation/CoreFoundation.h>. Foundation is an ObjC API (which is not compatible with C++). Core Foundation is a C API. When you include CoreFoundation, CFBundleGetMainBundle() should be fine. Note the CF at the start that is indicating it's part of Core Foundation, vs NS which indicates Foundation (or AppKit).
There is no need to rename this .mm. As long as you use CoreFoundation, it's fine to be a pure C++ file. Just remember that Core Foundation has its own memory management. There is no ARC. You need to remember to CFRelease anything you obtained using a function with Create or Copy in its name (or that you called CFRetain on. Full details are in the Memory Management Programming Guide for Core Foundation.
Related
Aside from recompiling rt.jar is there any way I can replace the currentTimeMillis() call with one of my own?
1# The right way to do it is use a Clock object and abstract time.
I know it but we'll be running code developed by an endless number of developers that have not implemented Clock or have made an implementation of their own.
2# Use a mock tool like JMockit to mock that class.
Even though that only works with Hotspot disabled -Xint and we have success using the code bellow it does not "persist" on external libraries. Meaning that you'd have to Mock it everywhere which, as the code is out of our control, is not feasible. All code under main() does return 0 milis (as from the example) but a new DateTime() will return the actual system millis.
#MockClass(realClass = System.class)
public class SystemMock extends MockUp<System> {
// returns 1970-01-01
#Mock public static long currentTimeMillis() { return 0; }
}
3# Re-declare System on start up by using -Xbootclasspath/p (edited)
While possible, and though you can create/alter methods, the one in question is declared as public static native long currentTimeMillis();. You cannot change it's declaration without digging into Sun's proprietary and native code which would make this an exercise of reverse engineering and hardly a stable approach.
All recent SUN JVM crash with the following error:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00000, pid=4668, tid=5736
4# Use a custom ClassLoader (new test as suggested on the comments)
While trivial to replace the system CL using -Djava.system.class.loader JVM actually loads up the custom classLoader resorting to the default classLoader and System is not even pushed trough the custom CL.
public class SimpleClassLoader extends ClassLoader {
public SimpleClassLoader(ClassLoader classLoader) {
super(classLoader);
}
#Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return super.loadClass(name);
}
}
We can see that java.lang.System is loaded from rt.jar using java -verbose:class
Line 15: [Loaded java.lang.System from C:\jdk1.7.0_25\jre\lib\rt.jar]
I'm running out of options.
Is there some approach I'm missing?
You could use an AspectJ compiler/weaver to compile/weave the problematic user code, replacing the calls to java.lang.System.currentTimeMillis() with your own code. The following aspect will just do that:
public aspect CurrentTimeInMillisMethodCallChanger {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0; //provide your own implementation returning a long
}
}
I'm not 100% sure if I oversee something here, but you can create your own System class like this:
public static class System {
static PrintStream err = System.err;
static InputStream in = System.in;
static PrintStream out = System.out;
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) {
System.arraycopy(src, srcPos, dest, destPos, length);
}
// ... and so on with all methods (currently 26) except `currentTimeMillis()`
static long currentTimeMillis() {
return 4711L; // Your application specific clock value
}
}
than import your own System class in every java file. Reorganize imports in Eclipse should do the trick.
And than all java files should use your applicatikon specific System class.
As I said, not a nice solution because you will need to maintain your System class whenever Java changes the original one. Also you must make sure, that always your class is used.
As discussed in the comments, it is possible that option #3 in the original question has actually worked, successfully replacing the default System class.
If that is true, then application code which calls currentTimeMillis() will be calling the replacement, as expected.
Perhaps unexpectedly, core classes like java.util.Timer would also get the replacement!
If all of the above are true, then the root cause of the crash could be the successful replacement of the System class.
To test, you could instead replace System with a copy that is functionally identical to the original to see if the crashes disappear.
Unfortunately, if this answer turns out to be correct, it would seem that we have a new question. :) It might go like this:
"How do you provide an altered System.currentTimeMillis() to application classes, but leave the default implementation in place for core classes?"
i've tried using javassist to remove the native currentTimeMills, add a pure java one and load it using bootclasspath/p, but i got the same exception access violation as you did. i believe that's probably because of the native method registerNatives that's called in the static block but it's really too much to disassemble the native library.
so, instead of changing the System.currentTimeMills, how about changing the user code? if the user code already compiled (you don't have source code), we can use tools like findbugs to identify the use of currentTimeMillis and reject the code (maybe we can even replace the call to currentTimeMills with your own implementation).
I need to use MFC Serialization mechanism to serialize objects of class Product:
class Product : public CObject
{
protected:
string name;
int expiring;
double price;
public:
Product();
~Product();
virtual void input_data();
virtual void print_data();
};
This is simple Windows Console Application. I got an error on CObject: not a class or struct name.
I tried to make MFC Console Application following the instruction in this comment: https://stackoverflow.com/a/50320168/6543699. Now I got a lot of errors (identifier not found or identifier not declared). The text of errors is in Russian, so I don't copy them here. This is how it looks:
I don't know anything about MFC using and can't find guide where it described clearly. My questions are:
1) Is it possible to use CObject in console application (non-MFC) and how?
2) If not, what should I do to be able to use MFC serialazation? Maybe include some headers or some components were just missing while installation?
You can just adjust a console app in a couple of steps to use MFC. First is to include afx.h, like:
#include <iostream>
#include <afx.h>
Then you will want to link with the MFC dynamic libraries.
Project Properties > Configuration Properties > Advanced > Use MFC
Select: Use MFC in a Shared DLL
It should now compile with CObject.
My note, I would not use MFC serialization, at the least use Boost Serialization I gave up using any serialization a long time ago because of the constant need to maintain versioning. I found it a night mare. Unless you see that your object structure will remain fairly static, I would recommend using XML to database your objects. It is a little more work to get going but way more often than not, you don't need to worry about versioning as you make changes.
I am trying to create a Vst3 plugin from a simple host app.
Here I have a simple code just to create an instance of a Vst3 plugin from a *.vst3 file.
auto proc = (GetFactoryProc)GetFunction(hmodule, "GetPluginFactory");
Steinberg::IPluginFactory* rawFactory = proc();
// Get factory info.
Steinberg::PFactoryInfo factoryInfo;
rawFactory->getFactoryInfo(&factoryInfo);
// Get classes.
for (size_t i = 0; i < rawFactory->countClasses(); i++)
{
Steinberg::PClassInfo info;
rawFactory->getClassInfo(i, &info);
// ------------------------------------
// ----------HOW TO USE THIS IDs-------
// ------------------------------------
Steinberg::FIDString cid = info.cid; // Is this correct?
Steinberg::FIDString iid = Steinberg::Vst::IComponent::iid; // I dont know what I am doing...
// ------------------------------------
// HOW TO USE THE createInstance FUNCTION?
// ------------------------------------
void* instance(nullptr);
Steinberg::tresult result = rawFactory->createInstance(cid, iid, &instance);
}
The questions is: What are this ids for? I can guess that cid stands for class-id. But what is the iid for and how can I get it to create an instance of a plugin class?
Every iid I take from any classes, IPluginFactory, IComponent and so on, I get unresolved external symbol.
The createInstance function return Steinberg::kNoInterface by the way so no classes is found when I try to insert an empty iid.
Anyone who know anything about Vst3 from Steinberg?
Any code example or documentation how to use the Vst3 for plugin hosting?
Thanks // Alex.
About module initialization.
A *.vst3 module may require additional initialization.
If a module exports some predefined functions, you should call it before getting the IPluginFactory.
The exported function names are "InitDll" and "ExitDll" for Windows platform.
// after the module is loaded.
auto initDll = (bool(*)())GetFunction(hmodule, "InitDll");
if(initDll) { initDll(); }
auto proc = (GetFactoryProc)GetFunction(hmodule, "GetPluginFactory");
Steinberg::IPluginFactory* rawFactory = proc();
// before the module is unloaded.
auto exitDll = (bool(*)())GetFunction(hmodule, "ExitDll");
if(exitDll) { exitDll(); }
You can also use VST3::Hosting::Module class defined in public.sdk/source/vst/hosting/module.h for this purpose.
About IDs.
The CID is the class-id (a.k.a. component-id) which is used for identifying the actual plugin component class in a vst3 module file.
A *.vst3 module file can contain multiple plugins however a host application can't identify a plugin by its actual C++ class name (because the host never knows it).
That's why the VST3 SDK provides the way to identify a actual plugin component class with CID.
The IID is the interface-id which is used for specifying a interface class.
In plugin loading context, IID represents which type of Interface class you want to get the created plugin as, normally it will be Vst::IComponent.
VST3 SDK is based on VST Module Architecture (VST-MA) which is very much like Component Object Model (COM) of Microsoft.
Learning COM will help you understand VST-MA.
Additionally, each plugins in a *.vst3 module file normally consist of two components: The Processor component and The EditController component.
The Processor component provides basic plugin APIs and DSP APIs.
The Processor component derives two interface classes: Vst::IComponent class and Vst::IAudioProcessor class.
The EditController component provides parameter management APIs and UI APIs.
Basic Conception
A VST 3 audio effect or instrument basically consists of two parts: a processing part and an edit controller part.
The corresponding interfaces are:
Processor : Steinberg::Vst::IAudioProcessor + Steinberg::Vst::IComponent
Controller : Steinberg::Vst::IEditController
The design of VST 3 suggests a complete separation of processor and edit controller by implementing two components. Splitting up an effect into these two parts requires some extra efforts for an implementation of course.
But this separation enables the host to run each component in a different context. It can even run them on different computers. Another benefit is that parameter changes can be separated when it comes to automation. While for processing these changes need to be transmitted in a sample accurate way, the GUI part can be updated with a much lower frequency and it can be shifted by the amount that results from any delay compensation or other processing offset.
A Plug-in that supports this separation has to set the Steinberg::Vst::kDistributable flag in the class info of the processor component (Steinberg::PClassInfo2::classFlags). Of course not every Plug-in can support this, for example if it depends deeply on resources that can not be easily moved to another computer. So when this flag is not set, the host must not try to separate the components in any way.
Although it is not recommended, it is possible to implement both, the processing part and the controller part in one component class. The host tries to query the Steinberg::Vst::IEditController interface after creating an Steinberg::Vst::IAudioProcessor and on success uses it as controller.
-- VST3 API Documentation (VST_SDK 3.6.13)
A plugins consists of two components, so you will call createInstance() twice.
This is the step to load a plugin from a *.vst3 module file:
Create the Processor component of the plugin from the module file, as Vst::IComponent class.
Initialize the Processor component.
Get the CID of the EditController component corresponding to the Processor component.
Create the EditController component from the module file with the CID.
Initialize the EditController component too.
Connect and setup them.
// Get classes.
for (size_t i = 0; i < rawFactory->countClasses(); i++)
{
Steinberg::PClassInfo info;
rawFactory->getClassInfo(i, &info);
// info.category will be kVstAudioEffectClass for Processor component.
// skip this component if not.
if(info.category != kVstAudioEffectClass) {
continue;
}
Vst::IComponent *comp(nullptr);
Steinberg::tresult result
= rawFactory->createInstance(info.cid, // tell factory which plugin to be created.
Vst::IComponent::iid, // tell factory which type of interface you want.
(void **)&comp // get the pointer to `comp`, and pass it as (void **)
);
if(result != kResultTrue) {
// TODO: error handling
return;
}
// now `comp` shall be valid pointer of Vst::IComponent.
// initialize comp
comp->setIoMode(Vst::IoModes::kAdvanced);
// you should define host context object before and pass it here as `FUnknown *`.
// the host context object is the class which normally derives Vst::IHostApplication,
// Vst::IComponentHandler, Vst::IPluginInterfaceSupport, etc.
comp->initialize(host_context);
TUID edit_cid;
comp->getControllerClassId(edit_cid);
// (in detail, IEditController interface may be obtained from IComponent directly if the plugin
// derives SingleComponentEffect.
// For such plugins, do not use this method and obtain IEditController with `comp->queryInstance()`
// )
Vst::IEditController *edit(nullptr);
result = rawFactory->createInstance(edit_cid,
Vst::IEditController::iid,
(void **)&edit);
if(result != kResultTrue) {
// TODO: error handling
return;
}
// initialize the EditController component too.
edit->initialize(host_context);
//...
// now the two components are created.
// connect and setup them.
// use the plugin.
// ...
// don't forget destruction after using it.
edit->terminate();
comp->terminate();
edit->release();
comp->release();
}
FYI, I develop an open-source VST3 Host Application called Terra.
https://github.com/hotwatermorning/Terra
It is still alpha version now. But it may be helpful for you.
Thank you.
I want to create a game engine as a training & portfolio project and the modular approach sounds promising but I have some problems with the module design.
First I want to create low level modules like Rendering, Application, Utility etc. and use them in high level modules like Terrain.
So the dependency would kinda look like this Game<-Engine<-Terrain<-Rendering.
I want to create multiple Rendering "sub modules" like Rendering.Direct3D11 and Rendering.OpenGL. That's where I would have circular dependencies. The sub modules would use interfaces of Rendering and Rendering would need to manage the sub modules, right?
Game<-Engine<-Terrain<-Rendering<-->Rendering.Direct3D11
I could probably create a module like RenderingInterfaces and break the circular dependency but that seems like a hacky workaround. I was planning to use the "sub module design" multiple times like for:
Game<-Engine<-Application<-->Application.Windows
Is the sub module design ugly? Is there a way to use the sub module design without circular dependencies?
You can solve this abstractly. Let's say you have three dylibs: Game.dll, Renderer.dll, SubRenderer.dll.
The renderer interface might look like this (simplified):
// Renderer.h
class SubRenderer
{
public:
virtual ~SubRenderer() {}
virtual void render() = 0;
};
class API Renderer
{
public:
explicit Renderer(SubRenderer* sub_renderer);
void render();
private:
SubRenderer* sub_renderer;
};
You can stick that in Renderer.h or something like that, and the Renderer constructor and render method can be implemented in Renderer.cpp which you include for the project that outputs Renderer.dll.
Now in SubRenderer.dll, you might have a function like this:
// SubRenderer.h
class SubRenderer;
API SubRenderer* create_opengl_renderer();
That can be implemented in SubRenderer.cpp which is compiled/linked to output `SubRenderer.dll. It might look like this:
// SubRenderer.cpp
#include "SubRenderer.h"
#include <Renderer.h>
class OpenGlRenderer: public SubRenderer
{
public:
virtual void render() override {...}
};
SubRenderer* create_opengl_renderer()
{
return new OpenGlRenderer;
}
Last but not least, in some source file in Game.dll, you can do something like this inside some Game.cpp:
// Game.cpp
#include <Renderer.h>
#include <SubRenderer.h>
int main()
{
SubRenderer* opengl_renderer = create_opengl_renderer();
Renderer renderer(opengl_renderer);
renderer.render(); // render a frame
...
delete opengl_renderer;
}
... of course hopefully with a safer design that conforms to RAII.
With this kind of system, you have these header dependencies:
`Game.cpp->Renderer.h`
`Game.cpp->SubRenderer.h`
`SubRenderer.cpp->Renderer.h`
In terms of module dependencies:
`Game.dll->Renderer.dll`
`Game.dll->SubRenderer.dll`
And that's it -- no circular dependencies anywhere. Game.dll depends on Renderer.dll and SubRenderer.dll, but Renderer.dll and SubRenderer.dll are completely independent of each other.
This works because this Renderer can use a SubRenderer given its virtual interface without knowing exactly what it is (thus requiring no dependencies to the concrete type of 'sub-renderer').
You can put Renderer.h somewhere that is centrally accessible from all three projects with a common include path (ex: inside an SDK directory). There is no need to duplicate it.
There shouldn't be any need for a reverse dependency in your design.
This is all about interfaces. Your rendering module need a native rendering API (sub-module, in your terms), but it shouldn't care if it is OpenGL or Direct3D11. The API sub-modules just have to expose a common API ; something like CreatePrimitiveFromResource(), RenderPrimitive()... These sub-modules shouldn't be aware of the upper layer, they just expose their common API.
In other words, the only "dependencies" needed is that the rendering module depends on a rendering sub-module (using the common interface), and the rendering sub-modules don't depend on anything (in your engine), they just expose a common interface.
Simple example :
We have a rendering module "IntRenderer" that renders integers. Its job is to convert integers to characters and print them. Now we want to have sub-modules "IntRenderer.Console" and "IntRenderer.Window", to print in a console or in a window.
With that, we define our interface : the sub-module must be a DLL that exports a function void print( const char * );.
This whole description is our interface ; it describes a common public face that all our int renderers sub-modules must have. Programmatically, you could say that the interface is just the function definition, but that's just a matter of terminology.
Now each sub-module can implement the interface :
// IntRenderer.Console
DLLEXPORT void print( const char *str ) {
printf(str);
}
// IntRenderer.Window
DLLEXPORT void print( const char *str ) {
AddTextToMyWindow(str);
}
With that, the int renderer can just use import a sub-module, and use printf(myFormattedInt);, regardless of the sub-module.
You can obviously define your interface as you want, with C++ polymorphism if you want.
Example : sub-modules X must be a DLL that exports a function CreateRenderer() that returns a class that inherit the class Renderer, and implements all its virtual functions.
Firstly please let me explain what I am trying to do:
I am using Qt to build an app mainly based on webkit. This app fetches content from internet and present it to user by traditional web way.
My app has to communicate many serial port devices, such as printer, IC card reader.
These serial port devices have different models, so that they have different communication protocol.
I want separate my app with the serial port devices communcating part, so that I can only update the communcation part without updating all the app.
Do I need to write a Qt plugin/webkit plugin, or some other way to do this? Any suggestions are welcome!
Thanks
AFAIK Qt already provides a plugin mechanism.
Check the QLibrary class out and the examples there.
For the serial port part qextserialport
Build your communication part in a dll/dynamic library by using TARGET = lib and CONFIG += dll in another qmake file.
I would suggest one of the PluginManager style plugin methods with C++.
I'm writing this from 2+ year old memory so it's meant only as a loose guide, not a definitive answer.
I have included a link to a site I used to get started on a project like you describe a few years ago. It worked well with the 40+ plugins we had available.
A search for [DLL plugin C++ class] should find several of the sites for you if you don't like the one I linked.
You will have to correct for your environment/compiler/OS etc.
In essence, assume you want the ability to Open, Read, Write and Close the serial ports in your plugins.
Create a pure virtual base class (Acts as something declared as an interface in Java):
/* This is the basic plugin header file that every plugin DLL has to include
Use your compilers pragmas/keywords to export the entire class from the DLL
In Microsoft land the keywords are _declspec( dllexport ) to export the class
from the base DLL and __declspec( dllimport ) to import the class into other
code. I'm using the MS keywords here because I don't remember how this is done
in other compilers. :)
*/
#if BUILDING_BASE_PLUGIN
/* You're compiling the DLL that exports the Plugin Base
#define BASE_DLL_EXPORT declspec( dllexport )
#else
/* You're compiling code that uses the plugin base
#define BASE_DLL_EXPORT declspec( dllimport )
#endif
class DLL_EXPORT SerialPortPluginBase
{
public:
enum SerialPortPluginError{ SUCCESS = 0, ERROR_1, ERROR_2, ERROR_ETC };
virtual SerialPortPluginError Open( /*Parameters*/ ) = 0;
virtual SerialPortPluginError Read( /*Parameters*/ ) = 0;
virtual SerialPortPluginError Write( /*Parameters*/ ) = 0;
virtual SerialPortPluginError Close( /*Parameters*/ ) = 0;
static std::string pluginName = "SerialPortPluginBase";
static int version;
};
In each plugin, implement the interface based on the above class as well as a method to register/unregister the DLL with a plugin manager (see the link below).
Each plugin should go in a separate DLL/SO.
See this site for a complete example.
Hope this helps. :)
What you want is to create a Qt Plugin for your application:
http://doc.qt.io/archives/qt-4.7/plugins-howto.html
You'll be able to extend your main application through a plugin. The only thing you'll need to add to your application is the process of load plugins and add some events to call plugins methods.