|
I finally got this to compile and it didn't leak.
PS. I hate STL too.
Anyone who thinks he has a better idea of what's good for people than people do is a swine.
- P.J. O'Rourke
-- modified at 2:20 Saturday 12th November, 2005
|
|
|
|
|
I am looking to learn how to implement non-simple callbacks to managed code unmanged C++. I can get a simple non-parametered callback examples working. But, I want to pass an object along for the ride through unamanged and have it show up as a parameter to the managed callback - perhaps the object will be in unmanaged code for along time before the callback - almost certainly during garbage collection. I would appreciate any help I can get - I know others have gocne through this and solved it.
Here is the code I am trying to use...
using namespace System;
using namespace System::Runtime::InteropServices;
#pragma unmanaged
// declare the unmanaged function prototype
typedef void (*MY_CALLBACK)(void *);
// Declaration of the unmanaged class
class CMyUnmanaged
{
public:
CMyUnmanaged() { }
// The unmanaged class method where the
// function pointer will be invoked.
void DoCallback( MY_CALLBACK myCallback, void *myParam )
{
// invoke the method
myCallback( myParam );
}
};
#pragma managed
namespace CallbackTest
{
// Protoype of the Delegate the matches the function pointer
// declaration the unmanaged code expects to receive.
public __delegate void CallbackDelegate( Object *obj );
// This is for marchalling the function pointer.
[StructLayoutAttribute( LayoutKind::Sequential, CharSet = CharSet::Unicode) ]
public __gc struct MyDelegate_Struc
{
[MarshalAsAttribute(UnmanagedType::FunctionPtr)]
CallbackDelegate* _Delegate;
};
// This is an attempt to marshall the object data we want to
// "pass through" unamanged code.
[StructLayoutAttribute( LayoutKind::Sequential, CharSet = CharSet::Unicode) ]
public __gc struct MyParam_Struc
{
[MarshalAsAttribute(UnmanagedType::Struct)]
Object* _Param;
};
// Managed class wrapper to be used for the callbacks.
public __gc class CMyManaged
{
private:
CMyUnmanaged __nogc *pUnManaged;
public:
CMyManaged()
{
// unmanaged class instance
pUnManaged = new CMyUnmanaged();
}
~CMyManaged()
{
// delete it because the GC won't
delete pUnManaged;
}
// here is where we try to get unmanaged code to invoke the callback.
void DoCallback( CallbackDelegate *pDelegate, Object * pObject )
{
// pin the object pointers
CallbackDelegate __pin *_cb = pDelegate;
Object __pin *_ob = pObject;
// these are the unmanaged types we need to pass
// to the unmanaged code that will be making the
// callback.
MY_CALLBACK fn;
void* ob;
// use interop to create the pointers we need
// from the objects we are passed.
// Create the Function Pointer
MyDelegate_Struc *s = new MyDelegate_Struc();
s->_Delegate = _cb;
Marshal::StructureToPtr( s, &fn, false );
// Attempt to create a void * pointer
MyParam_Struc *u = new MyParam_Struc();
u->_Param = _ob;
Marshal::StructureToPtr( u, &ob, false );
// make the method call (which fails...)
pUnManaged->DoCallback( fn, ob );
}
};
}
//
// and lastly the C# code that tries to run it all...
//
using System;
using CallbackTest;
namespace MyTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string _test = "Hello World";
CMyManaged cmm = new CMyManaged();
cmm.DoCallback( new CallbackDelegate( ThisCallback ), _test );
}
static void ThisCallback( Object obj )
{
Console.WriteLine( obj.ToString() );
}
};
}
You know neither the day nor the hour.
|
|
|
|
|
I want write a console program like this:
...
CMD> aaa <-- "aaa" is typed by user , without pressing [enter]
System : It is a msg <-- the system print msg for some event.
CMD> aaa <-- what i would like to ask is this :
"aaa" is still here and can be edited by user.
This should be a sigle-threaded, portable program.
the flow of this program is :
wait for any event or stdin input -> handle event -> wait event again ->...
I have no idea how to get user input without [ENTER] and print as editable text.
I have try conio , but it seems not portable...
Hope I will be helped. Thanks!
|
|
|
|
|
According to MSDN, getch is not standard C++, but _getch is ?
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
Hi all,
I developed windows form application using VC++.NET.
I have a check box that i need to know its status from another file. I can access it from the class file (using its name or this pointer) but i can't access it from another file within the project.
How can i do it?
I tried using the class namespace but no good.
Please help.
10'x
|
|
|
|
|
Your check box should be private, you shouldn't be able to access it outside the class. It sounds like this is so. You should expose a public method to get the state of the checkbox.
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
I need help using fstream...
i need to read a text file that has multiple lines, each line has the syntax:
'fname lname 01 02 03 04 05 06 07 08 08 10'
that is a first name space last name space and 10 test scores (separated by spaces). I then have to move all the data from one file to another except i have to add the average of the 10 scores to the end of each line...
I can read the full text and display as it is from one file to the other. The problem is i can't read just the numbers in order to get the average...here's the code i have so far...
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
using namespace std;
#define INPUTFILE "HW660-In.txt"
#define OUTPUTFILE "HW660-Out.txt"
void rwFiles(ifstream& inSource, ofstream& outSource);
bool goOn();
void main()
{
dispHeader();
do
{
ifstream inStudentRecord;
ofstream outStudentRecord;
inStudentRecord.open(INPUTFILE);
if (inStudentRecord.fail())
{
cout<<"Opening input file failed.\n";
exit(1);
};
outStudentRecord.open(OUTPUTFILE);
if (outStudentRecord.fail())
{
cout<<"Opening output file failed.\n";
exit(1);
};
rwFiles(inStudentRecord, outStudentRecord);
inStudentRecord.close();
outStudentRecord.close();
}while(goOn());
}
void dispHeader()
{
void rwFiles(ifstream& inSource, ofstream& outSource)
{
char next;
int iGrade = 0, oGrade = 0;
inSource.get(next);
while (!inSource.eof())
{
if(next == '\n')
{
cout<<" The End"; //this adds "The End" at the end of every line.
};
cout<<next;
outsource<<next;
="" insource.get(next);
="" };=""
}
bool="" goon()
{
="" char="" calcmore="Y" ;
="" bool="" goon="true;
" cout<<"would="" you="" like="" to="" continue?="" (y="" n)="" ";
="" cin="">>calcMore;
switch (calcMore)
{
case 'Y': case 'y': ;break;
case 'N': case 'n': default: goOn = false;
}
return goOn;
}
So basically all my code does is reads exactly what is in the input file and displays it to the screen as well as copies it to the output file.
noob in need of help...
|
|
|
|
|
If you know the format of the file, you can use the << operator to read the file into the appropriate variable types, which in this case is two strings, and 10 numeric types. As it stands, you're reading a char at a time. The real alternative to what I've suggested is to use getline and then munch the string to extract the data by looking for spaces and using substr and atoi to convert to ints.
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
In those situation stringstream can be cool!
http://www.cplusplus.com/ref/iostream/stringstream/[^]
Here is the code to read one line in your file and to compute the average score.
std::ifstream ifs("FileName", std::ios::in);
char buffer[255];
ifs.getline(buffer, 255);
std::istringstream iss(buffer);
char n1[255];
char n2[255];
double grade, mean=0.0;
int nGrade = 0;
iss >> n1 >> n2;
for(; iss >> grade; ++nGrade) mean += grade;
mean /= nGrade;
ifs.close();
// end
Now figure a way to do this for the whole file
Eric
Premature optimization is the root of all evil
|
|
|
|
|
qfegd wrote: In those situation stringstream can be cool!
and (IMHO) utterly superfluous...
there is already and input stream open in the form of the input file stream
why read a line convert it to another input stream and then use operator>> on that stream
as the input text file is rigorously defined why not use >> directly on the input file stream?
operator>> is overloaded for the inbuilt types & defaults
to consuming white space and newlines (thanks Bjarne)
thus...
char n1[255];<br />
char n2[255];<br />
double total, mean, grade;<br />
int count = 10;
<br />
ifstream in_file(IN_NAME);
<br />
while(!in_file.eof()) {<br />
in_file >> n1 >> n2;<br />
total = 0.0;<br />
for(int i = 0, i < count, ++i) {<br />
in_file >> grade;<br />
total += grade;<br />
}<br />
mean = total / count;<br />
}
i will leave writing to the output file for you (it can all be fitted into the above loop in 3 lines)
if your input file might be dirty you could add
in_file.ignore(255,'\n');
to ignore upto 255 characters at the end of the line and any new line.
hope this helps?
|
|
|
|
|
Christian Graus wrote: you can use the << operator to read
correction:
operator >> is overloaded to read the inbuilt types from an input stream
operator << is for writing to an output stream
|
|
|
|
|
I could use some help with a file i/o issue. I'm using simple fstream objects to read in a Unicode file, search it for a particular string, and print the line if it contains that string.
Here's a snippet of my function:
getline(traceFile, buffer); //pass getline the file stream object and string buffer
pos = buffer.find(hr, 0); //set the position of string hr if found
if (pos != string::npos)
outFile << "Line Number " << count <<":"<< buffer <
|
|
|
|
|
firstly a good unicode editor helps:
http://www.unipad.org/main/[^]
secondly the STL way is to convert to wide strings and streams
and (essential) use locales to 'imbue' them with the
ability to handle the unicode conversion that you desire
//include all the culture specific information you need
#include <locale>
//reveal the current locale
locale default_locale = wcout.getloc();<br />
cout << default_locale.name();
which if nothing has been imbued is C for classic
//create a new locale
locale french_locale("french");
//reveal its name
cout << french_locale.name();
//French_France.1253 in windows
//the names are non standard
//but the locales construct happily with intuitive language name or abbreviation
//see: http://www.microsoft.com/globaldev/nlsweb/default.asp[^]
//set a new locale
locale old_locale = wcout.imbue(french_locale);
use the widen and narrow methods to convert
and you should be away
a good code project article is here...
http://www.codeproject.com/vcpp/stl/upgradingstlappstounicode.asp?df=100&forumid=16224&exp=0&select=557556[^]
|
|
|
|
|
Hi all,
How can I use C++ object in C code?
Let's say an object is implemented by others in C++, but I want to use this object in my C code.
Is this possible?
Is there any trick I can use?
Thanks in advance!
--Tosh
|
|
|
|
|
I doubt this is possible....
even if you know the memory schema of an allocated object, you won't be able to access the members (for instance by dereferenciate a pointer to the address needed) if they were defined private or protected...
TOXCCT >>> GEII power [toxcct][VisualCalc]
|
|
|
|
|
You can do the following, create a .cpp file and put a extern "C" function into it. This function can access your CPP object and can also be called from your C file.
foo.cpp
--------
<br />
extern "C" int call_to_obj ()<br />
{<br />
return myObject.SomeMethod ();<br />
}<br />
I hope that helps.
-- modified at 6:12 Tuesday 17th January, 2006
|
|
|
|
|
i am a novice in game programming and i want to ask how
a program can read two keys simultaneously.
|
|
|
|
|
Direct Input, part of DirectX.
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
Train free @Microsoft
Got to this link and register free for
training your self for VS2005
https://www.microsoftelearning.com/visualstudio2005/
or
http://www.financialexpress.com/latest_full_story.php?content_id=107645
Microsoft dont give anything free except training
Vikas Amin
Embin Technology
Bombay
vikas.amin@embin.com
|
|
|
|
|
Hello...
I am having trouble setting the initial size of my SDI application. I thought that I would be able to override the PreCreateWindow() function in my MainFrame and reset the values of the CREATESTRUCT like this:
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
cs.cx = 1000;
cs.cy = 730;
if(!CFrameWnd::PreCreateWindow(cs))
return false;
return TRUE;
}
However, this does not work. I also tried the MoveWindow() function and SetWindowPos() function in the OnSize of CMainFrame. That looks like this..
void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
CFrameWnd::OnSize(nType, cy, cy);
if(!m_ResizeFlag)
{
MoveWindow(300, 300, 1000, 730);
m_ResizeFlag = true;
}
}
This did not work, either..
Any help would be MUCH appreciated!
Thanks in advance!
~SheriMarie
|
|
|
|
|
I add #include <windows.h> to stdafx.h file in windows form application and it dosent want to compile the project issuing this:
error C2039: 'GetObjectW' : is not a member of 'System::Resources::ResourceManager'
for this piece of code:
this->Icon = (__try_cast<system::drawing::icon *="">(resources->GetObject(S"$this.Icon")));
I just assigned new icon to my application and this code was added atomatically, but without #include <windows.h> it is compiled normally?
9ine
|
|
|
|
|
undefine GetObject and define a GetObject_T macro for calling the GetObjectA and GetObjectW API.
My blogs:
http://blog.joycode.com/jiangsheng
http://blog.csdn.net/jiangsheng
http://bloglines.com/public/jiangsheng
Command what is yours
Conquer what is not
---Kane
|
|
|
|
|
would you please indicate where should I undefine this macro and how to define another GetObject_T
9ine
|
|
|
|
|
another error with this code?
MessageBox::Show(this, S"err");
error C2653: 'MessageBoxW' : is not a class or namespace name
9ine
|
|
|
|
|
#undef MessageBox
#undef GetObject
My blogs:
http://blog.joycode.com/jiangsheng
http://blog.csdn.net/jiangsheng
http://bloglines.com/public/jiangsheng
Command what is yours
Conquer what is not
---Kane
|
|
|
|