In a typical com function which returns a string, people could make an error easily like the following one:
STDMETHODIMP MyClass::MyFunction(BSTR* pRet)
{
// This is how I return a string - is this incorrect?
std::string myString;
CComBSTR bstr (A2W (myString.c_str()));
*pRet = bstr;
return S_OK;
}
Issue with this is : while pRet points to the bstr , but bstr is defined inside the function scope, so when it goes out of the scope, the CComBSTR destructor will be called like this:
~CComBSTR() throw()
{
::SysFreeString(m_str);
}
which now makes pRet point to a dangling pointer.
An appropriate way is detach the m_str from the CComBSTR , so even when the destructor is called, the m_str won't be destroyed.
BSTR Detach() throw()
{
BSTR s = m_str;
m_str = NULL;
return s;
}
Some C++, C#, .Net, windows service, GIS thoughts posted by me. 有度量去容忍那些不能改变的事,有勇气去改变那些可能改变的事,有智慧去区分上述两件事。
Tuesday, October 25, 2005
Monday, October 10, 2005
Forward declaration of a template class.
Forward declaration of a template class.
This issue confused me a little bit when I try to declare a template-based class as a friend class of another class.
The issue is like this:
<template class T>
Class A
{
Public:
Private:
}
Class B
{
Public:
Private:
int m_b;
}
And Class A wants to access the private member m_b in Class B, the forward declaration of A will be like this:
template <class T> class A
This issue confused me a little bit when I try to declare a template-based class as a friend class of another class.
The issue is like this:
<template class T>
Class A
{
Public:
Private:
}
Class B
{
Public:
Private:
int m_b;
}
And Class A wants to access the private member m_b in Class B, the forward declaration of A will be like this:
template <class T> class A
Friday, October 07, 2005
Exception Handling Model
Exception Handling Model /Ehs and /Eha
The exception handling model specifies the model of exception handler used by the computer.
Eha : The exception handler catches the asynchronous structured exceptions and tells the compiler to assume that extern C function do throw an exception.
Ehs: The exception handler doesn’t catch the asynchronous exceptions and tells the compiler to assume that extern C functions do throw an exception.
Ehc: It can be used either with the Eha or Ehs, but it assumes that extern C functions never throw an exception.
The exception handling model specifies the model of exception handler used by the computer.
Eha : The exception handler catches the asynchronous structured exceptions and tells the compiler to assume that extern C function do throw an exception.
Ehs: The exception handler doesn’t catch the asynchronous exceptions and tells the compiler to assume that extern C functions do throw an exception.
Ehc: It can be used either with the Eha or Ehs, but it assumes that extern C functions never throw an exception.
XmlDocument.Load and XmlDocument.LoadXml
I was playing around the xml tree view control which I found from the codeproject, but keeping getting "The data at the root level is invalid".
Later on, I find I am confused between XmlDocument.Load and XmlDocument.LoadXml, the former always load an xml file based on the file name, while the later will accept the actual xml document.
Later on, I find I am confused between XmlDocument.Load and XmlDocument.LoadXml, the former always load an xml file based on the file name, while the later will accept the actual xml document.
JST Robust issue
JTS union may *not* be commutative or associative in the strict sense. In other words, different ordering of the operands may produce slightly different results. This is an unavoidable result of using finite-precision arithmetic to compute operations which inherently require higher precision.
The difference should normally be *very* minor, however. The one time this is not the case is when the first operation produces a robustness error. In this case obviously the two results can be very different (e.g. an exception, versus an actual return value).
> Is this simply a bug that has been fixed?
Yes, this probably reflects an improvement that was made in the intersection calculation.
> Should a union of two valid Geometry's always yield a valid Geometry?
Yes, if the operation completes successfully, the result will always be a valid Geometry. Unfortunately, in the current implementation, sometimes overlay operations can also result in robustness errors. (This is something I'm hoping to fix in a future release).
I notice that your data seems to be fairly limited in precision. You might try using a fixed precision model - this can sometimes alleviate robustness problems.
Martin Davis, Senior Technical Architect
Vivid Solutions Inc. www.vividsolutions.com
Suite #1A-2328 Government Street Victoria, B.C. V8T 5G5
Phone: (250) 385 6040 - Local 308 Fax: (250) 385 6046
The difference should normally be *very* minor, however. The one time this is not the case is when the first operation produces a robustness error. In this case obviously the two results can be very different (e.g. an exception, versus an actual return value).
> Is this simply a bug that has been fixed?
Yes, this probably reflects an improvement that was made in the intersection calculation.
> Should a union of two valid Geometry's always yield a valid Geometry?
Yes, if the operation completes successfully, the result will always be a valid Geometry. Unfortunately, in the current implementation, sometimes overlay operations can also result in robustness errors. (This is something I'm hoping to fix in a future release).
I notice that your data seems to be fairly limited in precision. You might try using a fixed precision model - this can sometimes alleviate robustness problems.
Martin Davis, Senior Technical Architect
Vivid Solutions Inc. www.vividsolutions.com
Suite #1A-2328 Government Street Victoria, B.C. V8T 5G5
Phone: (250) 385 6040 - Local 308 Fax: (250) 385 6046
Friday, August 12, 2005
Monday, August 08, 2005
BeginInvoke Method
BeginInvoke Method
BeginInvoke is a method of Control, and it executes a delegate asynchronously on the thread that the control's underlying handle was created on.
BeginInvoke is a method of Control, and it executes a delegate asynchronously on the thread that the control's underlying handle was created on.
Sunday, August 07, 2005
How virtual Memory works?
The virtual memory system allows only part of the memory required by the process to be resident in physical memory. Say, if a process requires 500 mb memory, but it may only have 20% memory sitting in physical memory, the other 80% may actually stay on the disk.
Demand Paging
1>When a process requests a block of memory, it check the internal page table for this process to determine whether the reference was a valid or invalid memory access.
2>If the reference is invalid, we terminate the process. If it was valid, but we have not yet brought in that page, we now page it in.
3>We find a free frame by taking one from the free-frame list.
4>We schedule a disk operation to read the desired page into the new allocated frame.
5>When the disk operation is complete, we modify the internal table kept with the process and the page table to indicate that the page is now in memory.
6>We restart the instruction that was interrupted by the illegal address trap.
Demand Paging
1>When a process requests a block of memory, it check the internal page table for this process to determine whether the reference was a valid or invalid memory access.
2>If the reference is invalid, we terminate the process. If it was valid, but we have not yet brought in that page, we now page it in.
3>We find a free frame by taking one from the free-frame list.
4>We schedule a disk operation to read the desired page into the new allocated frame.
5>When the disk operation is complete, we modify the internal table kept with the process and the page table to indicate that the page is now in memory.
6>We restart the instruction that was interrupted by the illegal address trap.
Paging
1>Paging allows the logically continuous memory to be scattered through the physical memory out of order.
2>Suppose the logical address space is 2**m, and the page size is 2**n, then the high order m-n bits are designated as page number, while the lower n bits are designated as offset after the particular physical page has been found.
3>The TLB is the quick look up to speed up the page table translation, it will quickly find the entry for the logical address. If the TLB is missing, then we need to look up the page table to find the right entry.
4>If the logical address space is very large, and the page size is relatively small, it will lead to a very large page table. We have to use a couple of techniques such as "multi level page table", "inverted page table" to reduce the size.
2>Suppose the logical address space is 2**m, and the page size is 2**n, then the high order m-n bits are designated as page number, while the lower n bits are designated as offset after the particular physical page has been found.
3>The TLB is the quick look up to speed up the page table translation, it will quickly find the entry for the logical address. If the TLB is missing, then we need to look up the page table to find the right entry.
4>If the logical address space is very large, and the page size is relatively small, it will lead to a very large page table. We have to use a couple of techniques such as "multi level page table", "inverted page table" to reduce the size.
Finalizer and Disposer
Finalizer is an implict cleanup, which relies on the GC to clean up the resources, while the disposer is explicit cleanup, which allows to clean up the resources explictly. The .Net supports both patterns, so it is very important to distinguish them. In general, explicit cleanup should be used favorably over the implict cleanup, since the resources are generally more precious than memory, we shouldn't really rely on the GC to hold it for long time and clean it after an unspecified time.
Annotation (Brian Grunkemeyer): There are two different concepts that are somewhat intertwined around object tear-down. The first is the end of the lifetime of a resource (such as a Win32 file handle), and the second is the end of the lifetime of the object holding the resource (such as an instance of FileStream). Unmanaged C++ provided destructors which ran deterministically when an object left scope, or when the programmer called delete on a pointer to an object. This would end the resource’s lifetime, and at least in the case of delete, end the lifetime of the object holding onto the resource. The CLR’s finalization support only allows you to run code at the end of the lifetime of the object holding a resource. Relying on finalization as the sole mechanism for cleaning up resources extends the resource’s lifetime to be equal to the lifetime of the object holding the resource, which can lead to problems if you need exclusive access to that resource or there are a finite number of them, and can hurt performance. Hence, witness the Dispose pattern for managed code, allowing you to define a method to explicitly mimic the determinism & eagerness of destructors in C++. This relegates finalization to a backstop against users of a type who do not call Dispose, which is a good thing considering the additional restrictions on finalizers.
In the Dispose(bool disposing) method, if the diposing passed in is true, it means that we can explicitely use other reference types that refer to other objects knowing for sure that those other objects have not been finalized or disposed yet. If it's false, we cannot refer to other resources since those objects may have already been freed.
When we inherit a class which has already correctly implemented "IDispose" pattern, we need only override the Dispose (bool disposing) class, we don't need to override the Finalize and Dipose class.
Annotation (Brian Grunkemeyer): There are two different concepts that are somewhat intertwined around object tear-down. The first is the end of the lifetime of a resource (such as a Win32 file handle), and the second is the end of the lifetime of the object holding the resource (such as an instance of FileStream). Unmanaged C++ provided destructors which ran deterministically when an object left scope, or when the programmer called delete on a pointer to an object. This would end the resource’s lifetime, and at least in the case of delete, end the lifetime of the object holding onto the resource. The CLR’s finalization support only allows you to run code at the end of the lifetime of the object holding a resource. Relying on finalization as the sole mechanism for cleaning up resources extends the resource’s lifetime to be equal to the lifetime of the object holding the resource, which can lead to problems if you need exclusive access to that resource or there are a finite number of them, and can hurt performance. Hence, witness the Dispose pattern for managed code, allowing you to define a method to explicitly mimic the determinism & eagerness of destructors in C++. This relegates finalization to a backstop against users of a type who do not call Dispose, which is a good thing considering the additional restrictions on finalizers.
In the Dispose(bool disposing) method, if the diposing passed in is true, it means that we can explicitely use other reference types that refer to other objects knowing for sure that those other objects have not been finalized or disposed yet. If it's false, we cannot refer to other resources since those objects may have already been freed.
When we inherit a class which has already correctly implemented "IDispose" pattern, we need only override the Dispose (bool disposing) class, we don't need to override the Finalize and Dipose class.
Saturday, August 06, 2005
Internal Fragmentation and External Fragmentation.
In the memory allocation model, if the memory is partitioned into the fixed size blocks[M bytes a block], then when a process(N bytes) is allocated into the memory, it will fit the first N/M blocks, and occupy the part of the last block, and this is called "internal fragmentation", since the fragment is internal to a block.
The other model is called "external fragmentation", the memory is NOT partitioned into the fixed size. It will maintain a free list of "available" memory blocks and select the best fit for the waiting process. The fragment is external to any occupied blocks so it is called external fragmentation.
The other model is called "external fragmentation", the memory is NOT partitioned into the fixed size. It will maintain a free list of "available" memory blocks and select the best fit for the waiting process. The fragment is external to any occupied blocks so it is called external fragmentation.
Wednesday, August 03, 2005
What is delegate in C#
Delegate is a class, NOT a method. It is a class inherited from System.Delegate or System.MulticastDelegate, which has two properties called "Target" and "Method". The target is the class instance on which the current delegate invokes the instance method, if it is null, it means it's a "Static" calling. MethodInvoker or EventHander are two special delegates treated in a fast manner by Invoke and BeginInvoke. MethodInvoker takes no parameters and returns no value, and EventHandler takes two parameters and returns no value.
Notifications
Notifications
It takes me a while to figure out why the legend control is not updated correctly until I found this sentence.
The applications that rely solely on WM_VSCROLL (and WM_HSCROLL) for scroll position data have a practical maximum position value of 65,535.
The GetScrollInfo function enables applications to use 32-bit scroll positions. Although the messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data, the functions SetScrollInfo and GetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.
To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK message in a WM_HSCROLL or WM_VSCROLL message, call GetScrollInfo with the SIF_TRACKPOS value in the fMask member of the SCROLLINFO structure. The function returns the tracking position of the scroll box in the nTrackPos member of the SCROLLINFO structure. This allows you to get the position of the scroll box as the user moves it. The following sample code illustrates the technique.
SCROLLINFO si;
case WM_HSCROLL:
switch(LOWORD(wparam)) {
case SB_THUMBTRACK:
// Initialize SCROLLINFO structure
ZeroMemory(&si, sizeof(SCROLLINFO));
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_TRACKPOS;
// Call GetScrollInfo to get current tracking
// position in si.nTrackPos
if (!GetScrollInfo(hwnd, SB_HORZ, &si) )
return 1; // GetScrollInfo failed
break;
.
.
.
}
It takes me a while to figure out why the legend control is not updated correctly until I found this sentence.
The applications that rely solely on WM_VSCROLL (and WM_HSCROLL) for scroll position data have a practical maximum position value of 65,535.
The GetScrollInfo function enables applications to use 32-bit scroll positions. Although the messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data, the functions SetScrollInfo and GetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.
To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK message in a WM_HSCROLL or WM_VSCROLL message, call GetScrollInfo with the SIF_TRACKPOS value in the fMask member of the SCROLLINFO structure. The function returns the tracking position of the scroll box in the nTrackPos member of the SCROLLINFO structure. This allows you to get the position of the scroll box as the user moves it. The following sample code illustrates the technique.
SCROLLINFO si;
case WM_HSCROLL:
switch(LOWORD(wparam)) {
case SB_THUMBTRACK:
// Initialize SCROLLINFO structure
ZeroMemory(&si, sizeof(SCROLLINFO));
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_TRACKPOS;
// Call GetScrollInfo to get current tracking
// position in si.nTrackPos
if (!GetScrollInfo(hwnd, SB_HORZ, &si) )
return 1; // GetScrollInfo failed
break;
.
.
.
}
Wednesday, July 27, 2005
Test the E9-1-1 Server.
It has been pretty stressful for me to write the testing code for the E9-1-1 server these days. Multithreading programming is always challenging, it's hard to debug, the code is flowing all around, and it's easy to make mistakes with those locks, monitors, wait handles. But it's also enjoyful to dig into those codes.
After finishing the test codes, the server part also needs extensively refactoring, the I/O completion port should be used to replace the polling, the so called "virtual multithreading" should be replaced by true multi-threading.
After finishing the test codes, the server part also needs extensively refactoring, the I/O completion port should be used to replace the polling, the so called "virtual multithreading" should be replaced by true multi-threading.
Tuesday, July 26, 2005
Bing will go to Hospitality and Tourism Management Program - College of Charleston
Hospitality and Tourism Management Program - College of Charleston
This blog is a little bit late, but still, I am very proud of him when I heard that he will head to College of Charleston to become a faculty.
Bing inspired me a lot in my life. When I was still at Nanjing University, I saw him get very high score in GRE, go abroad successfully, all of those things have a very good impact on my life.
After coming to states, we have choosing different roads. He is finishing his PH.D. and then go to Cornell , firstly in the CS master program, then transfer to a PostDoc in the Info Lab. I know his road is not smooth, but he goes through this step by step.
I hope he will do well in the future as a faculty, which he could be even 7 years ago in Nanjing University.
This blog is a little bit late, but still, I am very proud of him when I heard that he will head to College of Charleston to become a faculty.
Bing inspired me a lot in my life. When I was still at Nanjing University, I saw him get very high score in GRE, go abroad successfully, all of those things have a very good impact on my life.
After coming to states, we have choosing different roads. He is finishing his PH.D. and then go to Cornell , firstly in the CS master program, then transfer to a PostDoc in the Info Lab. I know his road is not smooth, but he goes through this step by step.
I hope he will do well in the future as a faculty, which he could be even 7 years ago in Nanjing University.
Wednesday, July 20, 2005
keyboard shortcut assignment in textbox
keyboard shortcut assignment in textbox
All 2 messages in topic - view as tree
I'm building a form to allow the user to assign a keyboard shortcut.
Basically I have a textbox that I want to work like the "Press shortcut
key(s)" in the Visual Studio keyboard options, the user does the key
combination and it shows up in the textbox. It looks like it works on the
KeyDown event. The KeyDown event has an argument of KeyEventArgs. The docs
say "You can use constants from Keys to extract information from the KeyData
property. Use the bitwise AND operator to compare data returned by KeyData
with constants in Keys to obtain information about which keys the user
pressed. To determine whether a specific modifier key was pressed, use the
Control, Shift, and Alt properties." Unfortunately there is no example and
I don't know how to do bitwise compares in c#. Can someone help me out
here?
thanks
Paul
first, set Form1.KeyPreview value to "true"
then, on Form's KeyDown Event
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs
e)
{
//Note: "T" is a sample designated shortcut key for textbox
if (e.Modifiers.ToString().ToUpper() == "ALT" &
e.KeyCode.ToString().ToUpper() == "T")
this.textBox1.Select();
}
gani
All 2 messages in topic - view as tree
I'm building a form to allow the user to assign a keyboard shortcut.
Basically I have a textbox that I want to work like the "Press shortcut
key(s)" in the Visual Studio keyboard options, the user does the key
combination and it shows up in the textbox. It looks like it works on the
KeyDown event. The KeyDown event has an argument of KeyEventArgs. The docs
say "You can use constants from Keys to extract information from the KeyData
property. Use the bitwise AND operator to compare data returned by KeyData
with constants in Keys to obtain information about which keys the user
pressed. To determine whether a specific modifier key was pressed, use the
Control, Shift, and Alt properties." Unfortunately there is no example and
I don't know how to do bitwise compares in c#. Can someone help me out
here?
thanks
Paul
first, set Form1.KeyPreview value to "true"
then, on Form's KeyDown Event
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs
e)
{
//Note: "T" is a sample designated shortcut key for textbox
if (e.Modifiers.ToString().ToUpper() == "ALT" &
e.KeyCode.ToString().ToUpper() == "T")
this.textBox1.Select();
}
gani
How Static Method works.
[Question:]
What if two users call the static method at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and shared for all users of the class?
[Answer:]
If the method is not accessing other static variables,
and is only working with references/values that are stored on the stack (in
other words, declared in the function), then you should have nothng to worry
about. The only thing you have to worry about at this point is other
resources you might be accessing (for example, the same file, if you are
working with files).
What if two users call the static method at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and shared for all users of the class?
[Answer:]
If the method is not accessing other static variables,
and is only working with references/values that are stored on the stack (in
other words, declared in the function), then you should have nothng to worry
about. The only thing you have to worry about at this point is other
resources you might be accessing (for example, the same file, if you are
working with files).
Tuesday, July 19, 2005
Can you find YY on this page?
Monday, July 18, 2005
The priorty date issue.
[Email from my attorney:
Jianwei
You are going to create a serious problem for yourself if you continue to try and use multiple avenues to push this along. The DOL and USCIS are going to start to push back. Up to now, I think your calls and actions have been just a question of impatience, but you are about to cross the line to a problem. I have seen cases where the agencies get calls from several sources, dig in their heels, and do nothing just to spite the individual because they feel there is too much pressure.
Please, I am serious. If you want me to work on this, you are going to have to back off and be patient. If you are convinced that you need to call dozens of people and push hard, I will be happy to submit a withdrawal letter, and you can handle it on your own. However, I can't do both. You need to make a decision whether you are going to handle your case on your own, or whether you want me to continue to work on it.
I called John today and left a voice mail. I will talk to him when he calls, and see what I can do to find out where in the process the information is stuck, if in fact it is stuck at all. But if you are going to make calls through Congressional offices, have the lawyer call, have the manager call, and check back a few days later for all, you are going to sabotage the process. I know that the government agencies will ignore the file if they think that is what is going on.
]
Well, I feel a little bit frustrating. I think Rob did a pretty good job on my case, and I don't have any issues with him. After all, the whole thing is not his responsbilty. But it still frustrates me, I have been waiting for this for the last three years, and every step seems to have a lot of pains. I adimit it is an issue because I have limited ability. If I am truley outstanding, I may not have to go through this painful process.
Life is life, you just have to live with it. If you spend more time improve yourself, there will be less pain ahead.
Jianwei
You are going to create a serious problem for yourself if you continue to try and use multiple avenues to push this along. The DOL and USCIS are going to start to push back. Up to now, I think your calls and actions have been just a question of impatience, but you are about to cross the line to a problem. I have seen cases where the agencies get calls from several sources, dig in their heels, and do nothing just to spite the individual because they feel there is too much pressure.
Please, I am serious. If you want me to work on this, you are going to have to back off and be patient. If you are convinced that you need to call dozens of people and push hard, I will be happy to submit a withdrawal letter, and you can handle it on your own. However, I can't do both. You need to make a decision whether you are going to handle your case on your own, or whether you want me to continue to work on it.
I called John today and left a voice mail. I will talk to him when he calls, and see what I can do to find out where in the process the information is stuck, if in fact it is stuck at all. But if you are going to make calls through Congressional offices, have the lawyer call, have the manager call, and check back a few days later for all, you are going to sabotage the process. I know that the government agencies will ignore the file if they think that is what is going on.
]
Well, I feel a little bit frustrating. I think Rob did a pretty good job on my case, and I don't have any issues with him. After all, the whole thing is not his responsbilty. But it still frustrates me, I have been waiting for this for the last three years, and every step seems to have a lot of pains. I adimit it is an issue because I have limited ability. If I am truley outstanding, I may not have to go through this painful process.
Life is life, you just have to live with it. If you spend more time improve yourself, there will be less pain ahead.
Subscribe to:
Posts (Atom)
