I am trying to call an unmanaged function for which I have documentation in C. I also have the C header file. It uses a large number of nested struct's that I am converting to Structure objects for VB.NET. In the callback delegate it sends a void* which I use to copy over to my Structure using Marshal.PtrToStructure. However, the result gives nearly everything as zeros so obviously I am not doing it correctly.
The structures are defined as:
typedef struct tagNET_TIME_EX
{
DWORD dwYear; // Year
DWORD dwMonth; // Month
DWORD dwDay; // Date
DWORD dwHour; // Hour
DWORD dwMinute; // Minute
DWORD dwSecond; // Second
DWORD dwMillisecond; // Millisecond
DWORD dwUTC; // utc query: zero means invaild, non-zero means vaild; set:invalid
DWORD dwReserved[1]; // reserved data
} NET_TIME_EX,*LPNET_TIME_EX;
and
typedef struct tagDEV_EVENT_FACERECOGNITION_INFO
{
int nChannelID; // ChannelId
char szName[128]; // event name
int nEventID; // event ID
NET_TIME_EX UTC; // the event happen time
DH_MSG_OBJECT stuObject; // have being detected object
...snip...
When I use the PtrToStructure, nearly everything after szName is 0.
Why is the UTC field declared as NET_TIME_EX instead of tagNET_TIME_EX? As far as I understand, the first is an instance while the second is a type. Should not the second structure be defined as:
typedef struct tagDEV_EVENT_FACERECOGNITION_INFO
{
int nChannelID; // ChannelId
char szName[128]; // event name
int nEventID; // event ID
tagNET_TIME_EX UTC; // the event happen time
DH_MSG_OBJECT stuObject; // have being detected object
...snip...
Such types of declarations are used at multiple places and perhaps that's what's causing the problem.
Related
Hello I am working on a small roboter project at uni and I have run into following issue.
I have a typedef called RoboterData inside of a header file because I want to make use of it across multiple files. Inside of the main file I have a RoboterData data variable which holds important data.
My goal is to have access from other files to this data having the ability to get and set it from another file. I want to avoid the use of a global variable.
Here are the relevant code fragments of my approach:
main.h
typedef struct {
DriveMode mode;
short sensor_left;
short sensor_mid;
short sensor_right;
int left_eng_speed;
int right_eng_speed;
} RoboterData;
main.c
# include "motors.h"
// The Data I want to get and set from other files.
RoboterData data;
// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
motors.h
void drive_straight(RoboterData *data);
motors.c
# include "main.h"
enum {
ENG_STILL = 0,
ENG_SLOW = 50,
ENG_MID = 155,
ENG_FAST = 200
}
void drive_straight(RoboterData *data) {
data ->left_eng_speed = ENG_FAST;
data ->right_eng_speed = ENG_FAST;
set_duty_cycle(LEFT_ENG, ENG_FAST);
set_duty_cycle(RIGHT_ENG, ENG_FAST);
}
When I later try to print out the values left_eng_speed and right_eng_speed via serial port it stays at 0. I know C is call by value but since I am passing a ptr to my struct the value I am passing is the adress of the struct and when I dereference it via '->' I should be able to access its original data from my understanding and not a copy because the only thing I copied was the address.
If someone could explain to me why this is not working and provide a viable alternative, I would be very greatfull.
// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
This is a function declaration. It doesn't do anything. You want
drive_straight(&data);
to actually call the function.
Though enums are integer constants, I have issue with usage/organizing.
I have organized serial data reception into three levels. Lowest level0 is an interrupt service routine, above that I have a function called receiveData() in level 1 and above that I have written processReceivedFrame() in level2. I have two enumerated types, one for level 0 and level 1 and the other is for level 2. Similarly one enum type for transmission.
enum FRAME_RECEIVE_STATUS
{
FR_STS_FRAME_NOT_RECEIVED=0, // Initial state by default
FRAME_RECEIVED, // Indicates that frame is received by interrupt vector
FIRST_START_BYTE_RECVD, // Set as soon as first start byte is received in case of multiple start bytes
RECV_PROGRESS, //Indicates that the receiving is in progress
INVALID_DATA_LENGTH, // This status is updated if length byte is invalid. We are verifying only against minimum possible length.
RX_BUFFER_FULL, // ISR will update this status in case buffer is full
INVALID_START_BYTE, // This will be set when first start byte is received, but second byte is incorrect.
FIRST_END_BYTE_RECEIVED, // Set as soon as first end byte is received.
};
enum FRAME_PROCESS_STATUS
{
FRAME_VALID=100,
FP_STS_FRAME_NOT_RECEIVED,
CHECKSUM_SUCCESS, //
CHECKSUM_ERROR,
};
enum TRANSMIT_STATES
{
FRAME_SEND_SUCCESS=0,
FRAME_SEND_RESPONSE_TIMEOUT,
FRAME_SEND_RESP_WAITING,
INVALID_RESPONSE_BYTE,
EXCEEDED_MAX_ATTEMPTS,
TRANSMIT_BUFFER_FULL,
};
But now I feel I have difficulty if I go for different enumerated types. Especially in level1, I end up in returning level two enum type, based on certain condition. In some places I get warnings if different type is used.
So usually what is the best way of using enumerated type for error handling? May be a single enumerated type for related functions such as one for reception (RECEIVE_STATES) and one for transmission (TRANSMIT_STATES)? But even in this case, we may end up in mixing differet types. For example, assume that I am transmitting some data and then waiting for response. The response may be RECEIVE_BUFFER_FULL of type enum RECEIVE_STATES. If the function return type is of enum TRANSMIT_STATES, but gets the enum of RECEIVE_STATES during the process, we may again have issues and handle that in code by replacing enum element of appropriate type. For example:-
enum TRANSMIT_STATES sendDataByte(char ); // Forward declaration.
enum RECEIVE_STATES receiveData(char *); // Forward declaration.
enum TRANSMIT_STATES transmitData(char *data)
{
for(.....)
{
enum TRANSMIT_STATES t_Status = sendDataByte(*(data+i)); // Transmit the data
if(t_Status==TRANSMIT_BUFFER_FULL)
return(t_Status);
}
// Wait for the response
enum RECEIVE_STATES r_Status = receiveData(data);
// Alternatively, t_Status = receiveData(data);
if(rStatus==RX_BUFFER_FULL)
t_Status=RX_BUFFER_FULL; // Assigning different type
return(t_Status);
}
In above code, if I go for:-
t_Status = receiveData();
I have issue of assigning different types. Even in case of:-
r_Status = receiveData(data);
I have to check the status and return appropriate code from TRANSMIT_STATES. I cannot have same enum element in two different types. So maintaining with different names is also an issue.
So in such case, one combined enum for all types of errors is suggested? But if we use some standard libraries for lower levels and those libraries may use different types of enums or normal int values. Here also I am not sure what is the recommended practice.
The simplest is to combine all the enums into one. A slightly more sophisticated approach is to use a "tagged union" aka variant:
enum ERROR_TYPE {
SUCCESS = 0,
TRANSMIT,
RECEIVE
};
struct result_t {
enum ERROR_TYPE err; // 0 means no error, i.e. success
union {
enum TRANSMIT_STATES err_send; // err 1
enum RECEIVE_STATES err_recv; // err 2
};
};
Then your code looks like this:
struct result_t transmitData(char *data)
{
struct result_t result = {SUCCESS};
for(...)
{
result.err_send = sendDataByte(*(data+i)); // Transmit the data
if(result.err_send==TRANSMIT_BUFFER_FULL) {
result.err = TRANSMIT;
return(result);
}
}
// Wait for the response
result.err_recv = receiveData(data);
if(result.err_recv==RX_BUFFER_FULL) {
result.err = RECEIVE;
}
return(result);
}
The structure looks like this
typedef struct _PROCESS_INFORMATION {
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
struct PLAYER
{
/* 0x0/0 */ struct PROCESS_INFORMATION *ProcessInformation;
/* 0x4/4 */ unsigned long dword4;
/* 0x8/8 */ unsigned long dword8;
/* 0xC/12 */ unsigned long dwordC;
//... Lots of fields here
}
Here is the prototype for TerminateProcess
BOOL WINAPI TerminateProcess(
_In_ HANDLE hProcess,
_In_ UINT uExitCode
);
I tried all 3 of these below and failed.
unsigned int v102; //exit code.
struct PLAYER *player; // eax#9
TerminateProcess(player->ProcessInformation->hProcess, v102);
TerminateProcess(player->ProcessInformation.hProcess, v102);
TerminateProcess(*(player->ProcessInformation)->hProcess, v102);
The arrow -> works for other members of the PLAYER struct pointer but if the member inside the struct PLAYER is a pointer to another struct then I get compiler problems.
All 3 above give me the compiler problems.
Maybe I had to use *LPPROCESS_INFORMATION inside the struct PLAYER or maybe I had to use struct _PROCESS_INFORMATION * because I really hate using typedef's
(yeah I just started using C only a week ago I usually code in Java/C#/VB.NET so this is all new to me.)
Edit: Seems I found the problem I was using a stupid typedef no wonder I had so much problems.. Those typedef's eliminate the use for a type which in this case is a struct so my structure was very screwed up..
Fix was to replace
/* 0x0/0 */ struct PROCESS_INFORMATION *ProcessInformation;
with
/* 0x0/0 */ struct _PROCESS_INFORMATION *ProcessInformation;
Now I can use the beautifiul arrows non-stop
player->ProcessInformation->hProcess
Is this right?
player->ProcessInformation->hProcess
is correct. Good luck!
Suppose there is a library function (can not modify) that accept a callback (function pointer) as its argument which will be called at some point in the future. My question: is there a way to store extra data along with the function pointer, so that when the callback is called, the extra data can be retrieved. The program is in c.
For example:
// callback's type, no argument
typedef void (*callback_t)();
// the library function
void regist_callback(callback_t cb);
// store data with the function pointer
callback_t store_data(callback_t cb, int data);
// retrieve data within the callback
int retrieve_data();
void my_callback() {
int a;
a = retrieve_data();
// do something with a ...
}
int my_func(...) {
// some variables that i want to pass to my_callback
int a;
// ... regist_callback may be called multiple times
regist_callback(store_data(my_callback, a));
// ...
}
The problem is because callback_t accept no argument. My idea is to generate a small piece of asm code each time to fill into regist_callback, when it is called, it can find the real callback and its data and store it on the stack (or some unused register), then jump to the real callback, and inside the callback, the data can be found.
pseudocode:
typedef struct {
// some asm code knows the following is the real callback
char trampoline_code[X];
callback_t real_callback;
int data;
} func_ptr_t;
callback_t store_data(callback_t cb, int data) {
// ... malloc a func_ptr_t
func_ptr_t * fpt = malloc(...);
// fill the trampoline_code, different machine and
// different calling conversion are different
// ...
fpt->real_callback = cb;
fpt->data = data;
return (callback_t)fpt;
}
int retrieve_data() {
// ... some asm code to retrive data on stack (or some register)
// and return
}
Is it reasonable? Is there any previous work done for such problem?
Unfortunately you're likely to be prohibited from executing your trampoline in more and more systems as time goes on, as executing data is a pretty common way of exploiting security vulnerabilities.
I'd start by reporting the bug to the author of the library. Everybody should know better than to offer a callback interface with no private data parameter.
Having such a limitation would make me think twice about how whether or not the library is reentrant. I would suggest ensuring you can only have one call outstanding at a time, and store the callback parameter in a global variable.
If you believe that the library is fit for use, then you could extend this by writing n different callback trampolines, each referring to their own global data, and wrap that up in some management API.
for the following libevent API:
void event_set(struct event *ev, int fd, short event, void (*cb)(int, short, void *), void *arg)
event_add(struct event *ev, const struct timeval *timeout);
struct event* event_new (struct event_base *, evutil_socket_t, short, event_callback_fn, void)
I want to know:
1) for pointer parameter ev in the second function event_add, the function event_add makes a local copy of the ev structure or not?
for example, if I do something like:
code snippet 1:
struct event ev;
event_set(&ev, ..para list 1...); // event 1
event_add(&ev, ...);
event_set(&ev, ..para list 2...); // event 2
event_add(&ev, ...);
event 1 is different from event 2 because parameter list 1 is different from parameter list 2. if event_add makes a local copy, then it is no problem, but if event_add doesn't make a local copy, then these two event_add actually add only event 2?
besides, if I have a main function:
void func(){
struct event ev;
event_set(&ev, ...);
event_add(&ev, ...)
}
int main(){
func();
event_base_dispatch(base);
}
after func() is called, the execution returns to main(). since ev is a local variable inside func(). if event_add(&ev,...) doesn't make a local copy, then ev is nowhere to find and there will be a problem.
so can I call event_add() on a local event structure?
I want to add many timer events(use something like evtimer_set) from time to time, and the adding happens in some callback functions. so I can't define global variabbles for the timeout events in advance, if event_add() can't be called on local variables, are there any solutions for this?
2) event_new returns a structure pointer, I want to know where is the structure, it is in a stack/heap memory or static memory?
MY special case::
in the main.c
int main(){
struct event_base *base;
struct event pcap_ev;
..... // here I get a file descriptor pcapfd
event_set(&pcap_ev, pcapfd, EV_READ|EV_PERSIST, on_capture, pcap_handle);
event_base_set(base, &pcap_ev);
event_add(&pcap_ev, NULL);
.....
event_base_dispatch(base);
}
on_capture callback function:
void *on_capture(int pcapfd, short op, void *arg)
{
pcap_t *handle;
handle = (pcap_t *)arg;
fqueue_t* pkt_queue;
pkt_queue = init_fqueue();
pcap_dispatch(handle, -1, collect_pkt, pkt_queue); // this function put all the cached packets into pkt_queue
process_pcap(pkt_queue);
}
the sub-routine process_pcap():
void process_pcap(pkt_queue);{
for (pkt in pkt_queue){ // here is pseudo code
insert(table, pkt); // here insert the pkt into a certain table
struct event pkt_ev;
evtimer_set(&pkt_ev, timer_cb, NULL); // I want to call timer_cb after timeout
event_base_set(base, &pkt_ev);
event_add(&pkt_ev, timeout);
}
}
the callback function timer_cb():
timer_cb(...){
if(...) delete(table, pkt);
.......
}
I'm just afraid timer_cb() won't be called because pkt_ev is a local variable.
You must use a different struct event instance for each event you want to know about. You can only call event_add() on a local struct event variable if that variable has a lifetime that spans across all calls to the event loop API up until it is removed with event_del().
The allocation functions default to the heap, but you can substitute your own allocation routines in its place with event_set_mem_functions().