In Gobject, how to override parent class's method belong to an interface? - glib

GObject class A implements interface IA, B is a derived class of A. How can B override A's method that is part of the interface IA?
Or, is this possible in GObject?
I know how to override parent class methods, but when inheritance meets interface, things seems to be more complicated.
Thanks a lot!

Yes, it is possible: just reimplement the interface as it was the first time, either using G_IMPLEMENT_INTERFACE() or manual initializing it in your get_type() function.
The real pain is if you need to chain up the old method. In this case, you should play with
g_type_interface_peek_parent to get the previous interface class.
Here is a test case:
/* gcc -otest `pkg-config --cflags --libs gobject-2.0` test.c */
#include <glib-object.h>
/* Interface */
#define TYPE_IFACE (iface_get_type())
typedef void Iface;
typedef struct {
GTypeInterface parent_class;
void (*action) (Iface *instance);
} IfaceClass;
GType
iface_get_type(void)
{
static GType type = 0;
if (G_UNLIKELY(type == 0)) {
const GTypeInfo info = {
sizeof(IfaceClass), 0,
};
type = g_type_register_static(G_TYPE_INTERFACE, "Iface", &info, 0);
}
return type;
}
void
iface_action(Iface *instance)
{
G_TYPE_INSTANCE_GET_INTERFACE(instance, TYPE_IFACE, IfaceClass)->
action(instance);
}
/* Base object */
#define TYPE_BASE (base_get_type())
typedef GObject Base;
typedef GObjectClass BaseClass;
static void
base_action(Iface *instance)
{
g_print("Running base action on a `%s' instance...\n",
g_type_name(G_TYPE_FROM_INSTANCE(instance)));
}
static void
base_iface_init(IfaceClass *iface)
{
iface->action = base_action;
}
G_DEFINE_TYPE_WITH_CODE(Base, base, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(TYPE_IFACE, base_iface_init));
static void
base_class_init(BaseClass *klass)
{
}
static void
base_init(Base *instance)
{
}
/* Derived object */
#define TYPE_DERIVED (derived_get_type())
typedef Base Derived;
typedef BaseClass DerivedClass;
static void
derived_action(Iface *instance)
{
IfaceClass *iface_class, *old_iface_class;
iface_class = G_TYPE_INSTANCE_GET_INTERFACE(instance, TYPE_IFACE, IfaceClass);
old_iface_class = g_type_interface_peek_parent(iface_class);
g_print("Running derived action on a `%s' instance...\n",
g_type_name(G_TYPE_FROM_INSTANCE(instance)));
/* Chain up the old method */
old_iface_class->action(instance);
}
static void
derived_iface_init(IfaceClass *iface)
{
iface->action = derived_action;
}
G_DEFINE_TYPE_WITH_CODE(Derived, derived, TYPE_BASE,
G_IMPLEMENT_INTERFACE(TYPE_IFACE, derived_iface_init));
static void
derived_class_init(DerivedClass *klass)
{
}
static void
derived_init(Derived *instance)
{
}
int
main()
{
GObject *object;
g_type_init();
object = g_object_new(TYPE_BASE, NULL);
iface_action((Iface *) object);
g_object_unref(object);
object = g_object_new(TYPE_DERIVED, NULL);
iface_action((Iface *) object);
g_object_unref(object);
return 0;
}

I think a better solution would be to make A's method virtual, rather than have B re-implement the interface A is attached to (this may require more work than just redefining one function), which you can do like this (example should be complete other than the fooable interface definition):
#include <glib-object.h>
#include "fooable.h"
typedef struct {GObject parent;} A;
typedef struct {
GObjectClass parent;
gint (*foo) (Fooable *self, gdouble quux);
} AClass;
#define TYPE_A (a_get_type())
#define A_CLASS(cls) (G_TYPE_CHECK_CLASS_CAST((cls), TYPE_A, AClass))
#define A_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), TYPE_A, AClass))
gint a_foo_real (Fooable *self, gdouble quux) {
g_print("a_foo_real(%g)\n", quux);
return 5;
}
gint a_foo (Fooable *self, gdouble quux) {
return A_GET_CLASS(self)->foo(self, quux);
}
void implement_fooable (FooableIface *iface) {iface->foo = a_foo;}
void a_class_init (AClass *cls) {cls->foo = a_foo_real;}
void a_init (A *self) {}
G_DEFINE_TYPE_WITH_CODE(A, a, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(TYPE_FOOABLE, implement_fooable));
/* derive class B from A */
typedef struct {A parent;} B;
typedef struct {AClass parent;} BClass;
#define TYPE_B (b_get_type())
gint b_foo_real (Fooable *self, gdouble quux) {
g_print("b_foo_real(%g)\n", quux);
return 55;
}
void b_class_init (BClass *cls) {A_CLASS(cls)->foo = b_foo_real;}
void b_init (B *self) {}
G_DEFINE_TYPE(B, b, TYPE_A);
int main () {
g_type_init();
A *a = g_object_new(TYPE_A, NULL);
B *b = g_object_new(TYPE_B, NULL);
fooable_foo(FOOABLE(a), 87.0); // a_foo_real(87.0) and returns 5
fooable_foo(FOOABLE(b), 32.0); // b_foo_real(32.0) and returns 55
return 0;
}
That's as brief of an example as I can make it. When you call fooable_foo() the function will look at its vtable for the function defined when you implemented the interface which is a_foo() which looks at A class's vtable to determine which function to actually call. The B class definition overrides A class's a_foo_real() with its own. If you need B class's b_foo_real to chain up, that's an easy enough (use A_CLASS(b_parent_class)->foo() which is defined for you in the G_DEFINE_TYPE macro)

Related

How to implement generic class spezialization in Dart

In Dart we can use generic classes [class]. We can also specialize those classes [class]. However at runtime the specialization is not used. (In C++ this is called template programming)
Example: The following code will result in the output
Hallo world
How are you
class MyClass<T> {
foo( print('Hallo world'); );
}
class MyClassInt implements MyClass<int> {
#override
foo( print('How are you'); );
}
main() {
MyClass<int> a = Myclass<int>();
MyClassInt b = MyClassInt();
a.foo();
b.foo();
}
How can the specialization (here type [int]) be done, that it is called at runtime, i.e.
main() {
MyClass<int> a = Myclass<int>();
a.foo();
}
should result in the outcome "How are you".
As mentioned by jamesdlin, Dart does not support specialization. But you can do something like this to make the illusion:
class MyClass<T> {
factory MyClass() {
if (T == int) {
return MyClassInt() as MyClass<T>;
} else {
return MyClass._();
}
}
// Hidden real constructor for MyClass
MyClass._();
void foo() {
print('Hallo world');
}
}
class MyClassInt implements MyClass<int> {
#override
void foo() {
print('How are you');
}
}
void main() {
final a = MyClass<int>();
final b = MyClassInt();
final c = MyClass<String>();
a.foo(); // How are you
b.foo(); // How are you
c.foo(); // Hallo world
}

How to implement the Delphi protected member access trick in C++ builder?

I need access to TControlItem.InternalSetLocation which is protected. I Delphi you would do
type
THackControlItem = class(TControlItem);
How do you do this in C++ Builder?
As in Delphi, you need to inherit the class but also override and make public the protected function. However, I wouldn't recommend to use it in production code.
class THackControlItem : public TControlItem
{
public:
void __fastcall InternalSetLocation(int AColumn, int ARow, bool APushed, bool MoveExisting)
{
TControlItem::InternalSetLocation(AColumn, ARow, APushed, MoveExisting);
}
};
In the program
TControlItem* ci = ...;
static_cast<THackControlItem*>(ci)->InternalSetLocation(...);
This is a nice trick I think Remy Lebeau showed me but can not find the QA anymore...
//---------------------------------------------------------------------------
#ifndef _TDirectMemoryStream
#define _TDirectMemoryStream
class TDirectMemoryStream:TMemoryStream // just for accessing protected SetPointer
{
public:
void SetMemory(BYTE *ptr,DWORD siz) { SetPointer(ptr,siz); Position=0; };
};
#endif
//---------------------------------------------------------------------------
You simply create new class that is descendant of the class you want to access. Now just add get/set functions for the protected members ...
Now usage:
TMemoryStream *mem=new TMemoryStream(); // original class instance you want to access
// overtype to our new class and access/use you get/set ...
((TDirectMemoryStream*)(mem))->SetMemory(hdr->lpData,hdr->dwBytesUsed);
delete mem; // release if not needed anymore
I am using it btw to feed a memory stream with custom memory data hdr coming from vfw camera so I can properly decode it using TJPEGImage class instead of writing the data into file and loading it back each frame ...
Here another example:
class A
{
protected:
int x;
public:
int getx(){ return x; }
};
class hack_A:A
{
public:
void setx(int _x){ x=_x; }
};
void test()
{
A a;
hack_A *ha=(hack_A*)&a;
ha->setx(10);
a.getx(); // print the x somwhere
}
However this will not work for private members ... In such case its doable too but requires access to A source code:
class A
{
protected:
int x;
private:
int y;
public:
int getx(){ return x; }
int gety(){ return y; }
friend class hack_A; // but this one requires access to A soourcecode
};
class hack_A:A
{
public:
void setx(int _x){ x=_x; }
void sety(int _y){ y=_y; }
};
void test()
{
A a;
hack_A *ha=(hack_A*)&a;
ha->setx(10);
ha->sety(20);
a.getx(); // print the x somwhere
a.gety(); // print the x somwhere
}

JNA to Go DLL - How do I get String returned from Go Func?

I have a Java program that is using JNA to call a Go Func. Here's the Interface to the Go func in Java:
public interface GPG extends Library {
// GoString class maps to: C type struct { const char *p; GoInt n; }
public class GoString extends Structure {
public static class ByValue extends GoString implements Structure.ByValue {}
public String p;
public long n;
protected List getFieldOrder(){
return Arrays.asList(new String[]{"p","n"});
}
}
// Foreign functions
public GoString.ByValue decrypt(GoString.ByValue encString, GoString.ByValue secretKeyring, GoString.ByValue passphrase);
}
The func signature in Go is:
func decrypt(encString string, secretKeyring string, passphrase string) string
The Go generated C header has:
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package command-line-arguments */
#line 1 "cgo-builtin-prolog"
#include <stddef.h> /* for ptrdiff_t below */
#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
#endif
/* Start of preamble from import "C" comments. */
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#line 1 "cgo-gcc-export-header-prolog"
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
typedef _GoString_ GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern GoString decrypt(GoString p0, GoString p1, GoString p2);
#ifdef __cplusplus
}
#endif
I call the Go Func from Java using this code:
GPG gpg = (GPG) Native.loadLibrary("C:/lib/gpg.dll", GPG.class);
GPG.GoString.ByValue encString = new GPG.GoString.ByValue();
encString.p = value;
encString.n = encString.p.length();
GPG.GoString.ByValue secretKeyring = new GPG.GoString.ByValue();
secretKeyring.p = "c:/gnupg/secring.gpg";
secretKeyring.n = secretKeyring.p.length();
GPG.GoString.ByValue passphrase = new GPG.GoString.ByValue();
passphrase.p = "SecretPassPhrase";
passphrase.n = passphrase.p.length();
GPG.GoString.ByValue decValue = gpg.decrypt(encString, secretKeyring, passphrase);
Clearly the func is being called and processes up to the return of the result string. But it then produces: "panic: runtime error: cgo result has Go pointer"
How do I get a String result back from Go?
Using go version go1.10 windows/amd64, JNA 4.5.1, Java 1.8.0_152
Your GO function should looks like this:
//export decrypt
func decrypt(encString string, secretKeyring string, passphrase string) *C.char {
//... your code here
var str string = "returning string"
return C.CString(str)
}
Java Interface:
public String decrypt(GoString.ByValue encString, GoString.ByValue secretKeyring, GoString.ByValue passphrase);
Your const char * in _GoString_ should use a Pointer instead, then use Pointer.getString() with the provided offset to obtain the actual string.
If Go itself is rejecting a string return value, you'll likely have to instead populate a buffer provided by the caller.

argument of pthread_create()

We know that we call pthread like this
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void* arg);
However, if in the start_routine function I wanna call has more than one argument, what can I do?
You can put whatever you want into a struct and pass a pointer to that.
In C:
typedef struct {
int a;
int b;
} ChildMainArgs;
void child_main(int a,int b);
void child_main_thread(void *arg)
{
ChildMainArgs *args_ptr = (ChildMainArgs *)arg;
child_main(args_ptr->a,args_ptr->b);
}
ChildMainArgs args;
args.a = 5;
args.b = 7;
pthread_create(..,..,child_main_thread,&args);

boost::asio and boost::bind errors

This questions is a bit annoying, I can't get the following code to compile. You will have to compile the code below.
I am having some trouble with boost asio, I am trying to abstract the logic of accepting connections into a uniform abstraction so that I can initiate connection for windows named-pipes and Unix domain sockets uniformly with regular TCP/IP.
There are 3 classes shown in the code below, the first 2 are the implementations of acceping TCP connections, and the third class below is a generic class that is implemented in terms of the first 2. I am having troubles with boost::bind calls. The trouble probably lies with my understanding of the semantics.
If I make TcpDestinationAcceptor::handle_accept a regular member function (--i.e., not a template member function) which results in me not passing the AcceptHandler parameter. The code compiles fine. Note: I do not remove the template function status from TcpDestinationAcceptor::StartAccepting.
Note: I have already started on a different design, still I would like to pursue this design if possible.
Self contained code:
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
class TcpDestinationConnection
{
public:
typedef boost::asio::ip::tcp::socket t_io_object;
TcpDestinationConnection(boost::asio::io_service & io_s)
: m_io_object(io_s) {} ;
t_io_object & io_object() { return m_io_object; }
private:
t_io_object m_io_object;
};
class TcpDestinationAcceptor
{
public:
typedef boost::asio::ip::tcp::acceptor t_acceptor;
typedef boost::shared_ptr<TcpDestinationConnection> t_connection_ptr;
TcpDestinationAcceptor( boost::asio::io_service & io_s)
: m_io_service(io_s),
m_acceptor(io_s)
{
m_acceptor.open(boost::asio::ip::tcp::v4());
}
TcpDestinationAcceptor( boost::asio::io_service & io_s ,
const boost::asio::ip::tcp::endpoint & endpoint)
: m_io_service(io_s),
m_acceptor(io_s, endpoint)
{
m_acceptor.open(boost::asio::ip::tcp::v4());
}
t_acceptor & acceptor() { return m_acceptor; }
template<typename AcceptHandler>
void StartAccepting(AcceptHandler h)
{
t_connection_ptr new_session(new TcpDestinationConnection(m_io_service));
m_acceptor.async_accept( new_session->io_object(),
boost::bind( &TcpDestinationAcceptor::handle_accept<AcceptHandler>, this,
boost::asio::placeholders::error, new_session, h));
}
template<typename AcceptHandler>
void handle_accept(const boost::system::error_code & err, t_connection_ptr cur, AcceptHandler h) {
}
private:
boost::asio::io_service & m_io_service;
boost::asio::ip::tcp::acceptor m_acceptor;
};
template<typename t_acceptor>
class ConnectionOracle
{
public:
ConnectionOracle()
: m_io_service(),
m_acceptor(m_io_service) {}
typename t_acceptor::t_acceptor & native_acceptor() { return m_acceptor.acceptor(); }
boost::asio::io_service & io_service() { return m_io_service; }
void StartConnection( typename t_acceptor::t_connection_ptr connection,
boost::system::error_code & error)
{
}
void Begin()
{
m_acceptor.StartAccepting( boost::bind( &ConnectionOracle::StartConnection,this,
_1,
boost::asio::placeholders::error));
m_io_service.run();
}
private:
boost::asio::io_service m_io_service;
t_acceptor m_acceptor;
};
int main()
{
ConnectionOracle<TcpDestinationAcceptor> ConOracle;
ConOracle.native_acceptor().
bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),50000));
ConOracle.Begin();
return 0;
}

Resources