Dynamic dispatch, C

最后都变了- 提交于 2019-12-11 23:35:21

问题


I am using the following scala code trying to translate this code into C using virtual method tables(dynamic dispatch).

this is the code in scala:

abstract class Node(n: String) {
  val id = Node.next
  var name: String = n
  def size: Int
  def nrNodes: Int = 1
  def find(q: String): Set[Node] = 
    if(name.contains(q)) Set(this) else Set()
}

My problem is with this part of the code:

def find(q: String): Set[Node] = 
        if(name.contains(q)) Set(this) else Set()

I am trying to translate it into C, and this is what I have so far:

Set find(Node *n, char * s){
 if(strstr(s,n->name)!=0){
   return (Set) n->name;
 }
 return ((Set (*)(Node *))  n->vtable[FIND])(n);
}

So find returns a set of nodes if it contains a Node else an empty set. when I run this it gives the following error:

error: unknown type name 'Set' 
use of undeclared identifier 'Set'

I am not sure if I have to use struct Set or my find method is wrong in general!

Here is my vtable:

enum Node_vtablekeys{
  SIZE=0,
  NRNODERS=1,
  FIND=2
};

回答1:


As said in the comments it seems that you forgot to declare your structure:

typedef struct _set
{
    // Whatever Set must contains
} Set;

Moreover, I don't really know Scala but in find() it looks like if you don't find a match, the function actually creates a new Set so I guess there should be a malloc in your function. Can you show us the scala Set structure ?

Depending of how you use find() it might be more useful to return a reference rather than the Set structure itself.

Set * find(Node *n, char * s)
{
    if(strstr(s,n->name)!=0)
    {
       return (Set) &(n->name);
    }
    else
    {
        Set * new_set = malloc(sizof(Set));
        // Copy attributes from n->vtable[FIND])(n) to new_set
        return new_set; 
    }
}


来源:https://stackoverflow.com/questions/22114217/dynamic-dispatch-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!